thread.isInterrupted()与Thread.interrupted()的区别
因为 thread.interrupted()相当于给线程发送了一个唤醒的信号,所以如果线程此时恰好处于
WAITING或者TIMED_WAITING状态,就会抛出一个InterruptedException,并且线程被唤醒。而如果
线程此时并没有被阻塞,则线程什么都不会做。但在后续,线程可以判断自己是否收到过其他线程发来的中断信号,然后做一些对应的处理。
这两个方法都是线程用来判断自己是否收到过中断信号的,前者是实例方法,后者是静态方法。二
者的区别在于,前者只是读取中断状态,不修改状态;后者不仅读取中断状态,还会重置中断标志位。
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(10);
myThread.interrupt();
Thread.sleep(7);
System.out.println("main中断状态检查-1:" + myThread.isInterrupted());
System.out.println("main中断状态检查-2:" + myThread.isInterrupted());
}
}
public class MyThread extends Thread {
@Override
public void run() {
int i = 0;
while (true) {
boolean interrupted = isInterrupted();
System.out.println("中断标记:" + interrupted);
++i;
if (i > 200) {
// 检查并重置中断标志。
boolean interrupted1 = Thread.interrupted();
System.out.println("重置中断状态:" + interrupted1);
interrupted1 = Thread.interrupted();
System.out.println("重置中断状态:" + interrupted1);
interrupted = isInterrupted();
System.out.println("中断标记:" + interrupted);
break;
}
}
}
}