gpt4 book ai didi

java - 为什么要捕获 InterruptedException 来调用 Thread.currentThread.interrupt()?

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:20 25 4
gpt4 key购买 nike

在 Effective Java(第 275 页)中,有这段代码:

...
for (int i = 0; i < concurrency; i++) {
executor.execute(new Runnable() {
public void run() {
ready.countDown();
try {
start.await();
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
}
}
...

捕获中断的异常只是为了重新引发它有什么用?为什么不让它飞起来?

最佳答案

简单的答案是 InterruptedException 是一个已检查的异常,它不在 Runnable.run 方法(或 Executable.execute( ) 方法)。所以你必须捕获它。一旦你捕获它,调用 Thread.interrupt() 来设置中断标志是推荐的做法......除非你真的打算压缩中断。

关于java - 为什么要捕获 InterruptedException 来调用 Thread.currentThread.interrupt()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1895881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com