AQS-ReentrantLock.CountDownLatch 源码

目录

1,countDownLatch(n)

2,await() 

2,countDown()


1,countDownLatch(n)

创建一个countDownLatch state=5

2,await() 

进入阻塞状态,直到state=0时,被唤醒

    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) // 若计算器的值 > 1 ,则进入阻塞状态
            doAcquireSharedInterruptibly(arg);
    }
    
    // 如果计数器的值=0,则返回1,否则返回-1进入阻塞状态
     protected int tryAcquireShared(int acquires) {
         return (getState() == 0) ? 1 : -1;
     }

    
    // 进入阻塞,直到计数器的值=0时 被唤醒
    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED); // 新增一个节点为共享类型,放入队尾(参考 lock源码分析)
        boolean failed = true;
        try {
            for (;;) { // 自旋直达状态=0
                final Node p = node.predecessor(); // 获取当前线程的前驱节点
                if (p == head) { // 若前驱节点为头结点
                    int r = tryAcquireShared(arg); // 判断计算器的值是否=0
                    if (r >= 0) { // 若计数器的值=0  r=1
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                // 若计数器的值>0,则进入阻塞状态(参考lock源码)
                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;
        }
    }


   

2,countDown()

每调用一次state-1 当state=0时,唤醒node节点对应的线程

    public void countDown() {
        sync.releaseShared(1);
    }

    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
    
    // 计数器值减到0时返回true
     protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
     }

    // 当计数器的值=0时,唤醒等待线程
    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;            // CAS 替换失败,则继续自旋
                    unparkSuccessor(h);  // unpark()node对象线程立即wait等待的线程
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // ???这里没有明白什么不在unparkSuccessor后直接退出
                break;
        }
    }
    
    // 唤醒节点对应的线程
    private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0) 
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {  // 从尾节点开始向前找到当前节点最近的一个阻塞的节点
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值