gpt4 book ai didi

java - 为什么我们不应该吞下 InterruptedException

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:57 25 4
gpt4 key购买 nike

我很困惑,无法理解为什么不应该吞下 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 block 中?

另外请解释一下上面的规则?

最佳答案

看看这个例子,我们假设它在线程/线程池上下文中运行。

public void run() {
// Honor interrupts so that you can stop/kill the task
while (!Thread.currentThread().interrupted()) {
this.doSomeChunkOfWork();
}
}

上面的代码是一个很好的例子,说明了如何编写一个可以被中断并分块处理数据的任务(想想从某些源读取数据并分部分处理数据)。现在让我们假设 doSomeChunkOfWork 被中断并且您捕获了一个异常。除非你再次设置标志或保持标志的中断状态,否则 run 方法将无法知道当方法调用返回时调用堆栈深处的处理被中断,这搞砸了我们的好逻辑。

这就是为什么您总是将状态设置回去,以便调用堆栈中的方法知道线程是否真的被中断了。我想为此做一个类比是“不要扫地毯下的污垢”。 :)

关于java - 为什么我们不应该吞下 InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com