问题描述
BlockingQueue有一个名为drainTo()的方法,但不会被阻塞。我需要一个队列,我想阻止,但也能够在一个单一的方法检索排队的对象。
BlockingQueue has the method called drainTo() but it is not blocked. I need a queue that I want to block but also able to retrieve queued objects in a single method.
Object first = blockingQueue.take();
if ( blockingQueue.size() > 0 )
blockingQueue.drainTo( list );
我想上面的代码会工作,但我正在寻找一个优雅的解决方案。
I guess the above code will work but I'm looking for an elegant solution.
推荐答案
您指的是:
我相信这指的是您的示例中的列表
/ p>
I believe that this refers to the collection list
in your example:
blockingQueue.drainTo(list);
意味着您不能修改列表
同时您正在从 blockingQueue
流入列表
。然而,阻塞队列在内部同步,所以当 drainTo
被调用时,(见下面的注释)如果它没有这样做,那么它不会是真正的线程安全的。您可以查看源代码,并验证 drainTo
是关于阻塞队列本身的线程安全。
meaning that you cannot modify list
at the same time you are draining from blockingQueue
into list
. However, the blocking queue internally synchronizes so that when drainTo
is called, (see note below) gets will block. If it did not do this, then it would not be truly Thread-safe. You can look at the source code and verify that drainTo
is Thread-safe regarding the blocking queue itself.
,你的意思是当你调用 drainTo
,你希望它阻塞,直到至少有一个对象被添加到队列?在这种情况下,除了:
Alternately, do you mean that when you call drainTo
that you want it to block until at least one object has been added to the queue? In that case, you have little choice other than:
list.add(blockingQueue.take());
blockingQueue.drainTo(list);
阻止,直到添加一个或多个项目,然后将整个队列排入集合 list
。
to block until one or more items have been added, and then drain the entire queue into the collection list
.
注意:从Java 7开始,get和puts使用单独的锁。现在,在drainTo(以及其他许多操作)中允许放置操作。
Note: As of Java 7, a separate lock is used for gets and puts. Put operations are now permitted during a drainTo (and a number of other take operations).
这篇关于BlockingQueue - 阻止drainTo()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!