首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在阻塞调用之前过早设置中断状态会导致无限循环?

为什么在阻塞调用之前过早设置中断状态会导致无限循环?
EN

Stack Overflow用户
提问于 2019-09-01 15:56:05
回答 1查看 57关注 0票数 0

我正在阅读“实践中的并发性”,在第6章的“响应中断”中说

过早设置中断状态可能导致无限循环,因为大多数可中断阻塞方法在进入时检查中断状态,如果设置了中断状态,则立即抛出InterruptedException。(可中断方法通常在阻塞或做任何重要工作之前轮询中断,以便在阻塞或做任何重要工作之前对中断作出同样的响应,从而尽可能地对中断作出响应)

代码语言:javascript
复制
public Task getNextTask(BlockingQueue<Task> 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();
        }
}

假设代码是

代码语言:javascript
复制
public Task getNextTask(BlockingQueue<task> queue){
boolean interrupted=false;
        while(true){
        /*i get this part that before the take() function threads     interrupted status is checked*/
            return queue.take();
        }catch(InterruptedException e){
                interrupted=true;
                Thread.currentThread().interrupt();
            }
    }//end of while
}

现在,为什么最后一个函数会导致无限循环,因为我已经将threrad的中断状态设置回false,根据我的理解,在阻塞调用轮询线程的中断状态期间,它将检查它是否设置为false,然后继续调用。那么无限循环是从哪里来的呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-01 16:58:34

因为take()方法会检查中断,所以会抛出InterruptedException。此检查/抛出通常采用以下形式:

代码语言:javascript
复制
if (Thread.currentThread.interrupted()) {  // Checks and clears the interrupted flag.
  throw new InterruptedException();
}

然后捕获InterruptedException,恢复中断标志,并再次调用take()。它检查中断,发现线程已被中断,然后抛出InterruptedException

然后捕获InterruptedException,恢复中断标志,并再次调用take()。它检查中断,发现线程已被中断,然后抛出InterruptedException

然后捕获InterruptedException,恢复中断标志,并再次调用take()。它检查中断,发现线程已被中断,然后抛出InterruptedException

等。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57744188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档