gpt4 book ai didi

java - 在退出前恢复中断的不可取消任务

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:25 24 4
gpt4 key购买 nike

我正在阅读一些 java 线程中断,但我不明白一些东西。希望有人会解释我。于是,就完成了下面的代码

public Integer getInteger(BlockingQueue<Integer> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
// fall through and retry
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}

解释如下:

Activities that do not support cancellation but still call interruptible blocking methods will have to call them in a loop, retrying when interruption is detected. In this case, they should save the interruption status locally and restore it just before returning, as shown in listing. rather than immediately upon catching InterruptedException. Setting the interrupted status too early could result in an infinite loop, because most interruptible blocking methods check the interrupted status on entry and throw InterruptedException immediately if it is set. (Interruptible methods usually poll for interruption before blocking or doing any significant work, so as to be as responsive to interruption as possible.)

不明白为什么要把中断状态保存到本地。
我很乐意听到一些解释。

最佳答案

根据设计,该方法永远不会抛出 InterruptedException。所以这意味着我们总是期望从队列中获取一个值。但是有人可能希望线程被中断,这就是为什么我们必须在最终从队列中获取值后保存-恢复中断状态。

因此,线程只有在从队列中取值后才能完成。

更新:查看take() 方法实现。它的第一条语句如下:

public final void acquireInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
...
}

关于java - 在退出前恢复中断的不可取消任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7751690/

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