java-无法取消的任务,在退出之前恢复中断

我正在阅读一些Java线程中断,但我听不懂一些东西.希望有人能解释我.因此,它完成了以下代码

 

 

public Integer getInteger(BlockingQueue 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-无法取消的任务,在退出之前恢复中断)