【发布时间】:2013-09-08 09:42:23
【问题描述】:
我很困惑,无法理解为什么不应该吞下 InterruptedException。
IBM 的文章说
当阻塞方法检测到中断并抛出 InterruptedException 时,它会清除中断状态。如果您捕获了 InterruptedException 但无法重新抛出它,您应该保留中断发生的证据以便调用堆栈上较高的代码可以了解中断并在需要时响应它
public class TaskRunner implements Runnable {
private BlockingQueue<Task> queue;
public TaskRunner(BlockingQueue<Task> queue) {
this.queue = queue;
}
public void run() {
try {
while (true) {
Task task = queue.take(10, TimeUnit.SECONDS);
task.execute();
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();//preserve the message
return;//Stop doing whatever I am doing and terminate
}
}
}
另外,Java 并发实践在第 7.1.3 章:响应中断中更详细地讨论了这一点。它的规则是:
只有实现线程中断策略的代码才能吞下中断请求。通用任务和库代码不应吞下中断请求。
1.谁能解释更高调用堆栈中的代码如何利用 Thread.currentThread().interrupt() 设置的状态;线程终止时在catch块中?
还请解释一下上面的规则?
【问题讨论】:
-
“这样调用堆栈上较高的代码可以了解中断并在需要时对其进行响应”的哪一部分您不明白吗?
-
@EJP 代码如何了解中断以及如何处理它。可能一个示例会有所帮助
标签: java concurrency interrupted-exception