首先我们要明白线程中断并不能终止该线程的执行,被中断的线程根据自己的中断状态自己处理。
举个例子。
你正在学习,妈妈大声跟你说来吃饭了(此时就调用了interrupt())方法。这时候你知道了,哦,可以吃饭了。但是我还是想写完这道题目再去吃饭。当你写完这道题目。调用 isInterrupted()方法 后,返回true。 原来有人告诉我已经可以吃饭了。好的。停止学习(中断线程)去吃饭。
好了,通过上面的例子我们知道。
interrupt(),只是用来设置线程的中断标志为true。这仅仅是设置中断而已,线程实际并没有中断。注意,当线程被join,sleep方法被阻塞而挂起,这时候用interrupt会抛出错误而返回。注意啊,最后还是会返回的。
isInterrupted()仅仅是检测当前线程是否被中断。
怎么来用呢?
while(!Thread.currentThread().isinterrupt()){
//做这道题目
}
一般就是来用作判断条件
interrupted() 使用要特别注意。他和isInterrupted()一样,也会返回中断状态。 但是,如果当前的线程被中断,就会清除中断标志。
来看下源码
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
注意,这是返回的是currentThread()
举个例子,
比如你在thread1线程中用thread1.interrupted() 和用thread2.interrupted() 是一样的。都是 对thread1使用的。不懂再看看上面的源码。