LinkedBlockingQueue 和 ConcurrentLinkedQueue 的区别与联系

更多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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐崇拜234

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值