⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 interruptthreaddemo2.java

📁 java入门经典教程 java入门经典教程 java入门经典教程
💻 JAVA
字号:
// 例4.4.2 InterruptThreadDemo2.java
class MyThread extends Thread
{
	boolean stop = false;   // 引入一个布尔型的共享变量stop
	public void run()
{
		while(!stop)    // 通过判断stop变量的值来确定是否继续执行线程体
{
			System.out.println(getName()+" is running");
			try
{
				sleep(1000);  
			}catch(InterruptedException e){
				System.out.println(e.getMessage());
}
		}
		System.out.println("Thread is exiting...");
	}
}
class InterruptThreadDemo2
{
	public static void main(String[] args) throws InterruptedException
{
		MyThread m=new MyThread();
		System.out.println("Starting thread...");
		m.start();
		Thread.sleep(3000);	
		System.out.println("Interrupt thread...");
		m.stop=true;	// 修改共享变量
		Thread.sleep(3000);  // 主线程休眠以观察线程中断后的情况
		System.out.println("Stopping application...");
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -