线程中断.

昨天试了试线程中断...代码如下:

public class Main extends Thread {
	@Override
	public void run() {
		while(!this.isInterrupted()){
			System.out.println("the thread is run ...");
			try {
				TimeUnit.SECONDS.sleep(1L);
			} catch (InterruptedException e) {
				e.printStackTrace(); // 开始没打印信息,就写了个 ignore
			}
		}
	}
	public void goOn(){
		Main.interrupted();	
		if(!this.isInterrupted()){
			run();
		}
	}
	public static void main(String[] args) throws InterruptedException{
		Main td = new Main();
		System.out.println("``````````````````````````````````````");
		td.start();
		TimeUnit.SECONDS.sleep(2L);
		System.out.println("use interrupt()...");
		td.interrupt(); // ...不好用?
		TimeUnit.SECONDS.sleep(4L);
		System.out.println("use goOn()...");
		td.goOn();
	}
}

总是出现非预期结果.... 原因是错误信息没有打印.后来经论坛哥们提醒,看了下jdk,发现:如果线程在调用 Object 类的 wait()wait(long)wait(long, int) 方法,或者该类的 join()join(long)join(long, int)sleep(long)sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException

你可能感兴趣的:(jdk,thread)