问题描述
我的问题与此问题有关先前问。在我使用生产者和消费者线程之间的通信的队列的情况下,人们通常建议使用 LinkedBlockingQueue
或 ConcurrentLinkedQueue
?
My question relates to this question asked earlier. In situations where I am using a queue for communication between producer and consumer threads would people generally recommend using LinkedBlockingQueue
or ConcurrentLinkedQueue
?
使用一个的优点/缺点是什么?
What are the advantages / disadvantages of using one over the other?
API的观点是 LinkedBlockingQueue
可以选择性地绑定。
The main difference I can see from an API perspective is that a LinkedBlockingQueue
can be optionally bounded.
推荐答案
对于生产者/消费者线程,我不确定 ConcurrentLinkedQueue
是一个合理的选项 - 它不实现 BlockingQueue
,这是生产者/消费者队列IMO的基本接口。你必须调用 poll()
,等待一点,如果你没有找到任何东西,然后再次轮询等...导致新项目延迟
For a producer/consumer thread, I'm not sure that ConcurrentLinkedQueue
is even a reasonable option - it doesn't implement BlockingQueue
, which is the fundamental interface for producer/consumer queues IMO. You'd have to call poll()
, wait a bit if you hadn't found anything, and then poll again etc... leading to delays when a new item comes in, and inefficiencies when it's empty (due to waking up unnecessarily from sleeps).
从BlockingQueue的文档中可以看出:
From the docs for BlockingQueue:
我知道这不会严格说,只有阻塞队列应该用于生产者 - 消费者队列,但即使如此...
I know it doesn't strictly say that only blocking queues should be used for producer-consumer queues, but even so...
这篇关于LinkedBlockingQueue vs ConcurrentLinkedQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!