LinkedBlockingQueue 阻塞问题

当用LinkedBlockingQueue的take()方法获取队列信息时

一旦队列为空,则进入阻塞状态

再往队列里put()元素,take()方法会自动获取新加入元素,还是始终保持阻塞状态?


幕布斯7119047
浏览 1431回答 4
4回答

白衣染霜花

自动获取,不会阻塞了

吃鸡游戏

如果还是阻塞,这个类还有什么用?

缥缈止盈

建议看看源码,就知道了,很有好处的

波斯汪

你采纳的答案是错误的。ConcurrentLinkedQueue是不阻塞的,LinkedBlockingQueue是阻塞的。分别给你上代码:如下:import java.util.concurrent.LinkedBlockingQueue;public class TestLinkedBlockingQueue {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; queue.put("a");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; queue.put("b");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.take());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.take());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.take());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; queue.put("c");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.take());&nbsp; &nbsp; &nbsp; &nbsp; } catch (InterruptedException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}//输出结果://a//b但是你再看非阻塞的ConcurrentLinkedQueueimport java.util.concurrent.ConcurrentLinkedQueue;public class TestConcurrentLinkedQueue {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();&nbsp; &nbsp; &nbsp; &nbsp; queue.add("a");&nbsp; &nbsp; &nbsp; &nbsp; queue.add("b");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.peek());&nbsp; &nbsp; &nbsp; &nbsp; queue.remove();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.peek());&nbsp; &nbsp; &nbsp; &nbsp; queue.remove();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.peek());&nbsp; &nbsp; &nbsp; &nbsp; queue.remove();&nbsp; &nbsp; &nbsp; &nbsp; queue.add("c");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(queue.peek());&nbsp; &nbsp; &nbsp; &nbsp; queue.remove();&nbsp; &nbsp; }}//a//b//null//Exception in thread "main" java.util.NoSuchElementException//&nbsp; &nbsp; at java.util.AbstractQueue.remove(AbstractQueue.java:117)//&nbsp; &nbsp; at TestConcurrentLinkedQueue.main(TestConcurrentLinkedQueue.java:14)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java