在什么条件下BlockingQueue.take会抛出中断的异常? [英] Under what conditions will BlockingQueue.take throw interrupted exception?

查看:2120
本文介绍了在什么条件下BlockingQueue.take会抛出中断的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个线程消耗由另一个线程产生的项目。它的run方法如下,其中inQueue是一个BlockingQueue

Let us suppose that I have a thread that consumes items produced by another thread. Its run method is as follows, with inQueue being a BlockingQueue

boolean shutdown = false;
while (!shutdown) {
    try {
        WorkItem w = inQueue.take();
        w.consume();
    } catch (InterruptedException e) { 
        shutdown = true;
    }
}

此外,不同的线程会发出没有通过中断这个运行的线程更多的工作项。如果不需要阻塞以检索下一个工作项,那么take()将抛出一个中断的异常。即如果生成器发出信号表明它已经填充了工作队列,是否可能意外地将一些项目留在inQueue中或者错过中断?

Furthermore, a different thread will signal that there are no more work items by interrupting this running thread. Will take() throw an interrupted exception if it does not need to block to retrieve the next work item. i.e. if the producer signals that it is done filling the work queue, is it possible to accidentally leave some items in inQueue or miss the interrupt?

推荐答案

阻塞队列信号终止的一个好方法是向队列中提交一个poison值,指示发生了关机。这确保了队列的预期行为得到满足。

A good way to signal termination of a blocking queue is to submit a 'poison' value into the queue that indicates a shutdown has occurred. This ensures that the expected behavior of the queue is honored. Calling Thread.interupt() is probably not a good idea if you care about clearing the queue.

提供一些代码:

boolean shutdown = false;
while (!shutdown) {
    try {
        WorkItem w = inQueue.take();
        if (w == QUEUE_IS_DEAD)
          shutdown = true;
        else
          w.consume();
    } catch (InterruptedException e) { 
        // possibly submit QUEUE_IS_DEAD to the queue
    }
}

这篇关于在什么条件下BlockingQueue.take会抛出中断的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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