在退出之前恢复中断的不可取消任务 [英] Noncancelable Task that Restores Interruption Before Exit

查看:472
本文介绍了在退出之前恢复中断的不可取消任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些java线程中断,我不明白一些东西。希望有人能解释我。所以,它完成了以下代码

I was reading some java thread interruption and I don't understand some stuff. Hope someone will explain me. So, it's done the following code

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();
    }
}

解释如下:


不支持取消但仍然可以调用
可中断阻止方法的活动必须在循环中调用它们
在检测到中断时重试。在这种情况下,他们应该在本地保存
中断状态并在返回之前恢复它,
如清单所示。而不是立即捕获
InterruptedException。太早设置中断状态可能
导致无限循环,因为大多数可中断阻塞
方法检查条目上的中断状态并立即抛出
InterruptedException(如果已设置)。 (可中断的方法
通常在阻止或执行任何重要的
工作之前轮询中断,以便尽可能地响应中断。)

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.)

我不明白为什么我们应该在本地保存中断状态。

我很乐意听到一些解释。

I don't understand why we should save the interrupted status locally.
I would be glad to hear some explanation.

推荐答案

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

By the design the method could not ever throw the InterruptedException. So it means we always expect take a value from the queue. But somebody could want the thread to be interrupted, that's why we have to save-restore the interrupted state after we have finally took a value from the queue.

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

So, the thread get finished only after taking a value from the queue.

UPDATE:查看 take()方法实现。它具有以下作为第一个语句:

UPDATE: Look into the take() method implementation. It has the following as the first statements:

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

这篇关于在退出之前恢复中断的不可取消任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆