addWaiter方法

    /**
     * Creates and enqueues node for current thread and given mode.
     * 将当前线程包装成节点加入等待队列,并指定排它/模式模式
     */
    private Node addWaiter(Node mode) {
        //1.创建节点,并指定排它/模式模式
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        //2.尝试用快速方式直接放到队尾。如果失败,则使用自旋方式添加。
        Node pred = tail;
        if (pred != null) {
            //与旧尾节点连接(新节点prev指向旧尾节点)
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                //与旧尾节点连接(旧尾节点next指向新节点)
                pred.next = node;
                return node;
            }
        }
        //3.通过自旋+CAS方式,将节点加入到队列尾部
        enq(node);
        return node;
    }

    /**
     * Inserts node into queue, initializing if necessary. See picture above.
     * 将节点入队列,必要时会进行初始化。
     */
    private Node enq(final Node node) {
        //自旋+CAS方式将节点加到队列尾部
        for (; ; ) {
            Node t = tail;
            //队列为空,则先初始化创建一个空节点,并将tail指针指向它
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {//队列非空,则插入队尾
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }
收藏 打印