问题描述
在Effective Java(第275页)中,有以下代码段:
In Effective Java (page 275), there is this code segment:
...
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();
}
}
}
...
为了重新加注它而捕获被中断的异常有什么用?为什么不让它飞起来?
What's the use of catching the interrupted exception just to re-raise it? Why not just let it fly?
推荐答案
简单的答案是 InterruptedException
是一个经过检查的异常,它不在的签名中Runnable.run
方法(或 Executable.execute()
方法。)所以你必须抓住它。一旦你抓住它,调用 Thread.interrupt()
来设置中断标志是推荐的事情......除非你真的打算压制中断。
The simple answer is that InterruptedException
is a checked exception and it is not in the signature of the Runnable.run
method (or the Executable.execute()
method). So you have to catch it. And once you've caught it, calling Thread.interrupt()
to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.
这篇关于为什么要捕获InterruptedException来调用Thread.currentThread.interrupt()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!