AQS-ReentrantLock.CountDownLatch 源码

    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    // 
     public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())  // 若被中断,则直接抛出异常
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
    
    // 如果状态值=0,则返回1
     protected int tryAcquireShared(int acquires) {
         return (getState() == 0) ? 1 : -1;
     }


    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED); // 新增一个节点为共享类型,放入队尾(参考 lock源码分析)
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor(); // 获取当前线程的前驱节点
                if (p == head) { // 若前驱节点为头结点
                    int r = tryAcquireShared(arg); // 判断是否全部释放完
                    if (r >= 0) { // 全部释放完  r=1
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

    private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; // Record old head for check below
        setHead(node); // 当前节点设置为头结点
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            Node s = node.next;
            if (s == null || s.isShared()) // 如果当前节点没有后续节点了
                doReleaseShared();
        }
    }

    private void doReleaseShared() {
        
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }


   

 

上一篇:


下一篇:ICS2020 简易调试器(一)