更多java源码分析请见:jdk11源码分析系列文章专栏:Java11源码分析
欢迎关注本人公众号
联系
LinkedBlockingQueue 与 ConcurrentLinkedQueue 都是先进先出 FIFO
的线程同步的队列。
阻塞队列
典型例子是 LinkedBlockingQueue
适用阻塞队列的好处:多线程操作共同的队列时不需要额外的同步,另外就是队列会自动平衡负载,即那边(生产与消费两边)处理快了就会被阻塞掉,从而减少两边的处理速度差距。
非阻塞队列
典型例子是 ConcurrentLinkedQueue
当许多线程共享访问一个公共集合时,ConcurrentLinkedQueue 是一个恰当的选择。
区别
The most important difference between LinkedBlockingQueue and ConcurrentLinkedQueue is that if you request an element from a LinkedBlockingQueue and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue will return right away with the behavior of an empty queue.
Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.
当没有数据时:
LinkedBlockingQueue 会阻塞,直到有元素进来;
ConcurrentLinkedQueue 立即返回空
适用性
LinkedBlockingQueue 多用于任务队列
ConcurrentLinkedQueue 多用于消息队列
单生产者,单消费者 用 LinkedBlockingqueue
多生产者,单消费者 用 LinkedBlockingqueue
单生产者 ,多消费者 用 ConcurrentLinkedQueue
多生产者 ,多消费者 用 ConcurrentLinkedQueue