interrupted
是一个静态方法,虽然其也用于判断当前线程是否被中断
,但是它和成员方法isInterrupted
还是有很大的区别的,调用该方法会直接擦除掉线程的interrupt标识
。
需要注意的是,如果当前线程被打断了,那么第一次调用interrupted
方法会返回true
,并且立即擦除了interrupt
标识;第二次包括以后的调用永远都会返回false
,除非在此期间线程又一次地被打断。
public class ThreadInterrupted {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
System.out.println(Thread.interrupted());
}
});
thread.setDaemon(true);
thread.start();
//shortly block make sure the thread is started.
TimeUnit.MILLISECONDS.sleep(2);
thread.interrupt();
}
}
……
false
false
true
false
false
……
在很多的false
包围中发现了一个true
,也就是interrupted
方法判断到了其被中断,立即擦除了中断标识,并且只有这一次返回true
,后面的都将会是false
。
-----------------------------------------------------------------------------读书笔记摘自书名:Java高并发编程详解:多线程与架构设计 作者:汪文君