Are LinkedBlockingQueue#39;s insert and remove methods thread safe?(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."
这篇关于LinkedBlockingQueue 的插入和删除方法是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LinkedBlockingQueue 的插入和删除方法是线程安全的吗?


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01