4 回答
TA贡献1811条经验 获得超4个赞
你采纳的答案是错误的。ConcurrentLinkedQueue是不阻塞的,LinkedBlockingQueue是阻塞的。分别给你上代码:如下:
import java.util.concurrent.LinkedBlockingQueue;
public class TestLinkedBlockingQueue {
public static void main(String[] args) {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
try {
queue.put("a");
queue.put("b");
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
queue.put("c");
System.out.println(queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//输出结果:
//a
//b
但是你再看非阻塞的ConcurrentLinkedQueue
import java.util.concurrent.ConcurrentLinkedQueue;
public class TestConcurrentLinkedQueue {
public static void main(String[] args) {
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
queue.add("a");
queue.add("b");
System.out.println(queue.peek());
queue.remove();
System.out.println(queue.peek());
queue.remove();
System.out.println(queue.peek());
queue.remove();
queue.add("c");
System.out.println(queue.peek());
queue.remove();
}
}
//a
//b
//null
//Exception in thread "main" java.util.NoSuchElementException
// at java.util.AbstractQueue.remove(AbstractQueue.java:117)
// at TestConcurrentLinkedQueue.main(TestConcurrentLinkedQueue.java:14)
添加回答
举报