[英]Why would you catch InterruptedException to call Thread.currentThread.interrupt()?
In Effective Java (page 275), there is this code segment: 在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();
}
}
}
...
What's the use of catching the interrupted exception just to re-raise it? 捕获被中断的异常只是为了重新提升它有什么用? Why not just let it fly? 为什么不让它飞?
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). 简单的答案是InterruptedException
是一个经过检查的异常,它不在Runnable.run
方法(或Executable.execute()
方法)的签名中。 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. 一旦你抓住它,调用Thread.interrupt()
来设置中断标志是建议的事情......除非你真的打算压缩中断。
Sometimes you can't ignore exception and you must catch it. 有时你不能忽视异常,你必须抓住它。 Mainly this happens when you override method which can't throw InterruptedException
in accordance with its signature. 当您重写不能根据其签名抛出InterruptedException
方法时,会发生这种情况。 For example, this approach is usually used in Runnable.run()
method. 例如,此方法通常用于Runnable.run()
方法。
The executor can interrupt tasks if they are cancelled but it clears the interrupted flag between tasks to avoid one cancelled task interrupting an unrelated task. 执行程序可以在取消任务时中断任务,但会清除任务之间的中断标志,以避免一个被取消的任务中断不相关的任务。
As such, interrupting the current thread here would be dangerous if it actually did anything. 因此,如果实际执行任何操作,在此处中断当前线程将是危险的。
A simpler way around this is to use Callable or ignore the interrupt. 更简单的方法是使用Callable或忽略中断。
Additionally it is a good idea to catch and log any error or exception thrown in the try/catch block otherwise the exception/error will be discarded and your program could be failing but you won't know it is or why. 另外,捕获并记录try / catch块中抛出的任何错误或异常是个好主意,否则异常/错误将被丢弃,您的程序可能会失败,但您不会知道它是什么或为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.