我很困惑,也无法理解为什么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块中设置的状态?
还请解释一下上面的规则?
发布于 2013-09-08 09:47:32
看看这个例子,让我们假设运行在线程/线程池上下文中。
public void run() {
// Honor interrupts so that you can stop/kill the task
while (!Thread.currentThread().interrupted()) {
this.doSomeChunkOfWork();
}
}上面的代码是一个很好的例子,说明您将如何编写一个任务,该任务可以被中断并以块的形式处理数据(例如从某个源读取数据并以部分方式处理数据)。现在让我们假设doSomeChunkOfWork被中断了,并且捕获了一个异常。除非您再次设置标志或维护标志的中断状态,否则run方法将无法知道在方法调用返回时,调用堆栈深处的处理被中断,这扰乱了我们的良好逻辑。
这就是为什么您总是将状态设置回原来的原因,以便调用堆栈中的方法能够知道线程是否真的被中断。我想用一个比喻来形容这是“不要在地毯下扫土”。:)
https://stackoverflow.com/questions/18682333
复制相似问题