Java 中 BlockingQueue 上的并发 put 调用
我知道并发添加到 c++ 中的 stl 队列可能会导致问题,解决此问题的方法是在所有添加/删除调用周围添加互斥锁。
但我现在正在用 Java 编程,并且正在使用 BlockingQueue。文档只说对 BlockingQueue 对象调用 put/take 的线程会被隐式阻塞,直到有空间可以放置/有东西可以分别取出。但是,它没有提及任何有关并发 put/take 调用的信息。我需要用互斥锁来保护它们吗?
I know that concurrent adds to an stl queue in c++ can cause issues, and the way to solve this is adding a mutex lock around all add/remove calls.
But I am programming in Java at the moment, and I'm using BlockingQueue. The documentation only says that the thread that calls put/take on a BlockingQueue object gets blocked implicitly until there's room to put/there's something to take respectively. However, it does not mention anything about concurrent put/take calls. Would I need to protect these with a mutex lock?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,阻塞队列是线程安全的。来自文档:
No, blocking-queues are thread-safe. From the docs:
来自文档:
因此,您不需要锁。
From the documentation:
Therefore, you don't need a lock.