如何阻塞直到BlockingQueue为空?

2024-04-24

我正在寻找一种方法来阻止直到BlockingQueue是空的。

我知道,在多线程环境下,只要有生产者将物品放入BlockingQueue,可能会出现队列变空,几纳秒后又充满项目的情况。

但是,如果只有one生产者,那么它可能希望在停止将项目放入队列后等待(并阻塞)直到队列为空。

Java/伪代码:

// Producer code
BlockingQueue queue = new BlockingQueue();

while (having some tasks to do) {
    queue.put(task);
}

queue.waitUntilEmpty(); // <-- how to do this?

print("Done");

你有什么主意吗?

EDIT: 我知道包装BlockingQueue并且使用额外的条件就可以解决问题,我只是问是否有一些预制的解决方案和/或更好的替代方案。


一个简单的解决方案使用wait() and notify():

// Producer:

// `sychronized` is necessary, otherwise `.notify` will not work
synchronized(queue) {
    while (!queue.isEmpty())
        queue.wait(); // wait for the queue to become empty
        // this is not a deadlock, because `.wait` will release the lock
    queue.put();
}

// Consumer:
synchronized(queue) {
    queue.get();
    if (queue.isEmpty())
        queue.notify(); // notify the producer
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何阻塞直到BlockingQueue为空? 的相关文章

随机推荐