Runnable.run InterruptedException中恢复的中断是如何传播到调用方方法的



代码如下:

import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
System.out.println(thread.isInterrupted());
}
}

有时System.out.println(thread.isInterrupted());打印true,有时打印false

那么,调用堆栈中更高级别的代码如何才能看到JCIP 5.4中描述的中断被发出呢?

这是一条路,但您的代码面临竞争条件。主线程在调用thread.interrupt()之后立即执行thread.isInterrupted()

文件指出

如果此线程在调用此类的[…]或sleep(long,int(方法时被阻塞,则其中断状态将被清除,并将收到InterruptedException。

给线程thread一个公平的机会来捕获异常并设置中断状态,即加入线程或至少等待一段时间。

最新更新