gpt4 book ai didi

java - 阻塞队列是否需要同步块(synchronized block)

转载 作者:行者123 更新时间:2023-11-30 06:41:31 24 4
gpt4 key购买 nike

public BlockingQueue<Message> Queue;
Queue = new LinkedBlockingQueue<>();

我知道如果我使用同步列表,我需要将它包围在同步块(synchronized block)中以跨线程安全地使用它

阻塞队列也是一样吗?

最佳答案

不,你不需要用同步块(synchronized block)包围。

来自JDK javadocs ...

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.

只是想指出,根据我的经验,JDK 的 java.util.concurrent 包中的类不需要同步块(synchronized block)。这些类为您管理并发性,并且通常是线程安全的。无论是否有意,java.util.concurrent 似乎已经取代了在现代 Java 代码中使用同步块(synchronized block)的需要。

关于java - 阻塞队列是否需要同步块(synchronized block),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com