并发编程(17)ConcurrentLinkedQueue

ConcurrentLinkedQueue是一个基于链接节点的无界线程安全队列,它采用先进先出的规则对节点进行排序。

offer()方法

public boolean offer(E e) {
    //检查节点是否为null
    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) {
            if (p.casNext(null, newNode)) {
                if (p != t) // hop two nodes at a time
                    casTail(t, newNode);  // Failure is OK.
                return true;
            }
        }
        //入列的同时也出列
        else if (p == q)
            //重新设置p
            p = (t != (t = tail)) ? t : head;
        else
            //tail已经不是最后一个节点,将p指向最后一个节点
            p = (p != t && t != (t = tail)) ? t : q;
    }
}

poll()方法

public E poll() {
    //出现p被删除的情况需要从head重新开始
    restartFromHead:
    for (;;) {
        for (Node<E> h = head, p = h, q;;) {
            E item = p.item;

            if (item != null && p.casItem(item, null)) {
                // Successful CAS is the linearization point
                // for item to be removed from this queue.
                if (p != h) // hop two nodes at a time
                    updateHead(h, ((q = p.next) != null) ? q : p);
                return item;
            }
            //队列为空
            else if ((q = p.next) == null) {
                //CAS更新head节点
                updateHead(h, p);
                return null;
            }
            //执行poll()方法时,另外一个线程已经把p元素删除
            else if (p == q)
                continue restartFromHead;
            else
                p = q;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq40988670/article/details/86620043