BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #59347同步于 2018/6/7
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

【问题】LinkedBlockingQueue 和 ConcurrentLinkedQueue使用场

f741048125
2018/6/7镜像同步4 回复
LinkedBlockingQueue的代码是用两个lock实现: ReentrantLock takeLock = new ReentrantLock()和ReentrantLock putLock = new ReentrantLock();put()/take()是阻塞的,都说很适合生产者/消费者,或者任务队列,但用锁的话当并发量很大会影响性能; ConcurrentLinkedQueue是基于CAS的,主要是对head、tail的操作,CAS失败之后还可以别的线程协助完成,我的理解是ConcurrentLinkedQueue就是一个高度并发的Queue,但需要自己解决返回值为null的问题。 疑问:ConcurrentLinkedQueue应该也可以用在生产者/消费者中吧?这样的话多个生产者、多个消费者时不需要等待,性能岂不更好?它们各自都有什么优点缺点?它们在使用时分别擅长怎样的情景?
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
flymop机器人#1 · 2018/6/8
As for it not being a BlockingQueue, well, blocking a thread to wait on a queue is a freakishly terrible way of designing concurrent systems. Don't. If you can't figure out how to use a ConcurrentLinkedQueue in a consumer/producer scenario from:https://stackoverflow.com/questions/1426754/linkedblockingqueue-vs-concurrentlinkedqueue
Julkot机器人#2 · 2018/6/14
Blockingqueue的优点在于可中断的阻塞,特别适合生产者消费者模型,当队列满或者空时,能够让生产者和消费者阻塞,这样可以简化你的实现,否则如果你用cocurrentlinkedqueue自己实现的话,阻塞逻辑你得自己实现 【 在 flymop 的大作中提到: 】 : As for it not being a BlockingQueue, well, blocking a thread to wait on a queue is a freakishly terrible way of designing concurrent systems. Don't. If you can't figure out how to use a ConcurrentLinkedQueue in a consumer/producer scenario : : from:https://stackoverflow.com/questions/1426754/linkedblockingqueue-vs-concurrentlinkedqueue
Nroskill机器人#3 · 2018/6/14
楼上说的没错,补充一点第二个为什么稍微不好用 实际实现消费者的时候,如果使用第二种且队列为空,消费者会一直自旋占用cpu资源,而第一种不会
zhaoxiyuan机器人#4 · 2018/6/17
今天也是刚把queue刷了一遍,看了看源代码,实际中还没有用到。