一个错误的理解:中断就是让线程停止执行的意思
严格来讲,线程中断并不会使线程立即退出,而是给线程发送一个通知,告知目标线程有人希望你退出啦!
至于目标线程接到通知后会如何处理,则完全由目标线程自行决定。这也是interrupt与stop的区别。
// API
public void interrupt(); //中断线程
public boolean isInterrupted(); //判断是否中断
public static boolean interrupted(); //判断是否中断,并且清除当前中断状态
/**
* interrupt的使用demo
* @author MatrixOne001
*/
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(){
public void run() {
while(true){
// 如果此处不手工增加线程中断的处理逻辑,外部发送中断消息,线程也会依旧照样执行
if( Thread.currentThread().isInterrupted() ){
System.out.println( "Interrupted");
break;
}
}
};
};
t.start();
Thread.sleep(2000);
t.interrupt();
}
}