简介
是一个适用于高并发场景下的队列,通过无锁的方式,实现了高并发状态下的高性能,通常ConcurrentLinkedQueue性能好于BlockingQueue.它是一个基于链接节点的无界线程安全队列。该队列的元素遵循先进先出的原则。头是最先加入的,尾是最近加入的,该队列不允许null元素。
使用
add 和offer() 都是加入元素的方法(在ConcurrentLinkedQueue中这俩个方法没有任何区别)
poll() 和peek() 都是取头元素节点,区别在于前者会删除元素,后者不会。
public class ThreadQueue {
public static void main(String[] args) {
//无界队列,非阻塞
ConcurrentLinkedQueue<String> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
concurrentLinkedQueue.offer("张三");//添加一个值
concurrentLinkedQueue.offer("王五");
System.out.println(concurrentLinkedQueue.poll());
System.out.println(concurrentLinkedQueue.size());
System.out.println(concurrentLinkedQueue.peek());
System.out.println(concurrentLinkedQueue.size());
}
}