public static void main(String[] args) {
ConcurrentLinkedQueue<Integer> concurrentLinkedQueue = new ConcurrentLinkedQueue<>();
// 三大操作 均是并发安全的
boolean add1 = concurrentLinkedQueue.add(1);
System.out.println(add1);
boolean add2 = concurrentLinkedQueue.add(2);
System.out.println(add2);
Integer poll = concurrentLinkedQueue.poll();
System.out.println(poll);
boolean contains = concurrentLinkedQueue.contains(2);
System.out.println(contains);
}
因为没有实现BlockingQueue接口,所以是非阻塞队列。
怎么用CAS操作来实现插入正确性
先修改next的指定值再修改tali指针
随着线程增多,CAS一直判断十分消耗CPU,此时CAS性能会大幅度降低,因为CPU此时一直循环并没有做别有意义的事情。
ConcurrentLinkedQueue之add方法
public boolean offer(E e) {
final Node<E> newNode = new Node<E>(Objects.requireNonNull(e));
for (Node<E> t = tail, p = t;;) {
Node<E> q = p.next;
if (q == null) {
// p is last node
if (NEXT.compareAndSet(p, null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this queue,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time; failure is OK
TAIL.weakCompareAndSet(this, t, newNode);
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}
通过自旋的方式,进行插入操作,不是阻塞队列。