我很困惑,不明白为什么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.有人能解释一下当线程被终止时,如何使高调用堆栈中的代码利用在catch块中由Thread.currentThread().interrupt()设置的状态吗?
请解释上述规则。