适用于高并发下对集合类进行操作的场景。
常用的线程安全方法有offer,add,poll,peek,底层通过cas 实现对容器的原子操作。
一个很简单的使用例子如下:
public class ConcurrentLinkedQueueTest { private static Queue<String> coupons = new ConcurrentLinkedQueue<>(); public static void main(String[] args) { for (int i=1; i<=500; i++) { coupons.add("优惠券"+i); } for (int i=0; i<10; i++) { new Thread(() -> { while (true) { /** 取出并remove队列中的head元素,队列空的话返回null */ String coupon = coupons.poll(); if (coupon != null) { System.out.println(coupon + "被领走了"); } else { break; } } }).start(); } } }