LinkedBlockingQueue 的插入和删除方法是线程安全的吗? [英] Are LinkedBlockingQueue's insert and remove methods thread safe?

查看:19
本文介绍了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.

我的问题是,我是否需要同步访问 addtake.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 的插入和删除方法是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆