JUC中多线程的集合——ConcurrentLinkedQueue

转载

https://blog.csdn.net/qq_38293564/article/details/80798310

原理

入队列操作
在这里插入图片描述
代码如下

    public boolean offer(E e) {
    
    
        checkNotNull(e);
        final Node<E> newNode = new Node<E>(e);

        for (Node<E> t = tail, p = t;;) {
    
    
            Node<E> q = p.next;
            if (q == null) {
    
    
                // p is last node
                if (p.casNext(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
                        casTail(t, newNode);  // Failure is OK.
                    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;
        }
    }

出队操作

在这里插入图片描述

    public E poll() {
    
    
        restartFromHead:
        for (;;) {
    
    
            for (Node<E> h = head, p = h, q;;) {
    
    
                E item = p.item;

                if (item != null && p.casItem(item, null)) {
    
    //比较当前head节点是item,然后把iterm出来
                    // Successful CAS is the linearization point
                    // for item to be removed from this queue.
                    if (p != h) // hop two nodes at a time
                        //采用CAS的方式调整head。
                        updateHead(h, ((q = p.next) != null) ? q : p);
                    return item;
                }
                else if ((q = p.next) == null) {
    
    
                    updateHead(h, p);
                    return null;
                }
                else if (p == q)
                    continue restartFromHead;
                else
                    p = q;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/define_us/article/details/111649675