为什么要捕获 InterruptedException 来调用 Thread.currentThread.interrupt()?
在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();
}
}
}
...
捕获中断的异常只是为了重新引发它有什么用?为什么不让它飞呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简单的答案是,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 theRunnable.run
method (or theExecutable.execute()
method). So you have to catch it. And once you've caught it, callingThread.interrupt()
to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.有时你不能忽略异常,你必须捕获它。主要是当您重写无法根据其签名抛出 InterruptedException 的方法时,会发生这种情况。例如,这种方法通常用在 Runnable.run() 方法中。
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. For example, this approach is usually used inRunnable.run()
method.如果任务被取消,执行器可以中断任务,但它会清除任务之间的中断标志,以避免一个已取消的任务中断不相关的任务。
因此,如果当前线程确实做了任何事情,那么在这里中断它将会很危险。
解决此问题的一种更简单的方法是使用 Callable 或忽略中断。
此外,捕获并记录 try/catch 块中引发的任何错误或异常是一个好主意,否则异常/错误将被丢弃,并且您的程序可能会失败,但您不会知道它是什么或为什么。
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.
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.