本文介绍了如何阻塞直到BlockingQueue为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种阻止方式,直到 BlockingQueue 为空。

I'm looking for a way to block until a BlockingQueue is empty.

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

I know that, in a multithreaded environment, as long as there are producers putting items into the BlockingQueue, there can be situations in which the queue becomes empty and a few nanoseconds later it is full of items.

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

But, if there's only one producer, then it may want to wait (and block) until the queue is empty after it has stopped putting items into the queue.

Java /伪代码:

Java/Pseudocode:

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

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

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

print("Done");

您有任何想法吗?

编辑:我知道包装 BlockingQueue 并使用附加条件可以解决问题,我只是问是否有一些预制的解决方案和/或更好的选择。

EDIT: I know that wrapping BlockingQueue and using an extra condition would do the trick, I'm just asking if there are some pre-made solutions and/or better alternatives.

推荐答案

使用 wait()和 notify()

// Producer:
synchronized(queue) {
    while (!queue.isEmpty())
        queue.wait(); //wait for the queue to become empty
    queue.put();
}

//Consumer:
synchronized(queue) {
    queue.get();
    if (queue.isEmpty())
        queue.notify(); // notify the producer
}

这篇关于如何阻塞直到BlockingQueue为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 01:49