gpt4 book ai didi

java - 哪些代码可以吞掉interruptedException?

转载 作者:搜寻专家 更新时间:2023-10-31 20:32:26 25 4
gpt4 key购买 nike

我在实践中阅读了并发性。现在我想了解如何处理 InterrruptedException

书中的建议:

- Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or
- Restore the interruption status so that code higher up on the call stack can deal with it.
- Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.

前两个陈述对我来说很清楚,但我不明白第三个。你能澄清一下吗?最好提供示例。

更新(感谢 Shubham 的链接)

The one time it is acceptable to swallow an interrupt is when you know the thread is about to exit. This scenario only occurs when the class calling the interruptible method is part of a Thread, not a Runnable or general-purpose library code, as illustrated in Listing 5. It creates a thread that enumerates prime numbers until it is interrupted and allows the thread to exit upon interruption. The prime-seeking loop checks for interruption in two places: once by polling the isInterrupted() method in the header of the while loop and once when it calls the blocking BlockingQueue.put() method.

public class PrimeProducer extends Thread {
private final BlockingQueue<BigInteger> queue;

PrimeProducer(BlockingQueue<BigInteger> queue) {
this.queue = queue;
}

public void run() {
try {
BigInteger p = BigInteger.ONE;
while (!Thread.currentThread().isInterrupted())
queue.put(p = p.nextProbablePrime());
} catch (InterruptedException consumed) {
/* Allow thread to exit */
}
}

public void cancel() { interrupt(); }
}

我现在不明白加粗的文字。

最佳答案

简答:如果你能应对这种情况,那就忍着吧。

中断异常发生在并行线程中发生的进程被取消或中断时。因此,如果您是唯一对这个事实感兴趣的人,并且您可以处理线程“死”的情况,那么您可以接受它。

这在现实生活中是完全可能的。该策略取决于每种情况。

关于java - 哪些代码可以吞掉interruptedException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42219790/

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