如下代码片段:
Thread thread = new Thread(){
public void run(){
System.out.println("thread");
}
};
thread.start();
thread.interrupt();
System.out.println("end");
调用了interrupt方法却没有产生中断的原因:
对线程的interrupt是对线程处在sleep,wait,join状态的时候才起作用。InterruptException不interrupt()方法抛出的,interrupt()只改变线程的中断状态,sleep,wait,join的内部会不停的检查线程中断状态,如果它们检查到线程处于中断状态,就抛出异常中断线程。如果你的线程不处于这3个状态中,调用interrupt不会中断线程,或者说不会马上中断线程,如果后面的代码有让线程进入上面3个状态的其中一个,线程会马上抛出InterruptException而中断,因为你之前的interrupt()调用改变了线程的内部状态。
我们可以通过如下例子来来看效果:
Thread thread = new Thread(){
public void run(){
System.out.println("thread");//
try {
Thread.sleep(20000);
} catch (InterruptedException e) {//在主线程里主动调用中断,所以这里还没等睡够就会被叫起来,产生中断异常
e.printStackTrace();
}
}
};
thread.start();
thread.interrupt();//这里主线程会执行下来,而thread也会执行它自己的东西,这里将线程的中断状态改变,那么等到出遇到thread里的sleep时就会产生中断
System.out.println("end");
}