LinkedBlockingQueue 的插入和删除方法是线程安全的吗?
我在两个不同的线程之间使用 LinkedBlockingQueue
.一个线程通过add
添加数据,而另一个线程通过take
接收数据.
I'm using LinkedBlockingQueue
between two different threads. One thread adds data via add
, while the other thread receives data via take
.
我的问题是,我是否需要同步访问 add
和 take
.LinkedBlockingQueue
的插入和删除方法是线程安全的吗?
My question is, do I need to synchronize access to add
and take
. Is LinkedBlockingQueue
's insert and remove methods thread safe?
推荐答案
是的.来自文档:
"BlockingQueue 的实现是线程安全的.所有排队方法使用原子地实现它们的效果内部锁或其他形式的并发控制.然而,大宗集合操作 addAll,containsAll、retainAll 和 removeAll不一定执行除非另有说明,否则原子地在一个实现中.所以它是可能的,例如,对于 addAll(c)之后失败(抛出异常)只添加一些元素c."
"BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c."
相关文章