JUC源码解析:CountDownLatch

CountDownLatch用于倒计时,每个线程对计数器减1,当减到0以后,才能执行继续往下执行,否则阻塞。比如,统计一个Excel文件内的数据,有多个sheet,只有每个sheet都统计完成,最后才能对整个Excel文件进行统计;又比如,公司部门团建,需要先在公司集合,一共10个人,只有10个人都集合后,才能坐大巴去目的地,只要有一个人没到达,大巴车就得一直等着。

public class CountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(()->{
            countDownLatch.countDown();
            System.out.println("thread1,当前countDownLatch值为:" + countDownLatch.getCount());
        },"thread1").start();
        new Thread(()->{
            countDownLatch.countDown();
            System.out.println("thread2,当前countDownLatch值为:" + countDownLatch.getCount());
        },"thread2").start();
        new Thread(()->{
            countDownLatch.countDown();
            System.out.println("thread3,当前countDownLatch值为:" + countDownLatch.getCount());
        },"thread3").start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("当前countDownLatch值为:" + countDownLatch.getCount());
    }
}
CountDownLatch类图

首先new CountDownLatch(3)点进去

public CountDownLatch(int count) {
   if (count < 0) throw new IllegalArgumentException("count < 0");
   this.sync = new Sync(count);
}
//继承了AQS类,state是AQS类的锁状态,即线程重入次数
Sync(int count) {
     setState(count);
}

countDown方法

public void countDown() {
    //看方法名就知道,是共享锁
    sync.releaseShared(1);
}
//AQS类的方法
public final boolean releaseShared(int arg) {
  //释放共享锁,state减1,当state减到0后,满足if条件
  if (tryReleaseShared(arg)) {
      //释放共享锁
      doReleaseShared();
      return true;
   }
   //如果state已经等于0,或者state减1后不等于0,返回false
   return false;
}
protected boolean tryReleaseShared(int releases) {
    // Decrement count; signal when transition to zero
    for (;;) {
      //获取当前state值
      int c = getState();
      //如果state等于0,表示锁没有被占用,返回false
      if (c == 0)
          return false;
      //否则将state-1
      int nextc = c-1;
      //CAS修改state的值,将state值减1,如果CAS失败,说明已经别的线程修改了state值,则再次循环
      if (compareAndSetState(c, nextc))
          //如果state减1后的值是0,返回true,否则返回false
          return nextc == 0;
    }
}
//AQS类方法
private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            //获取头节点
            Node h = head;
            //如果同步队列有至少2个节点
            if (h != null && h != tail) {
                //头节点的waitStatus
                int ws = h.waitStatus;
                //如果头节点的waitStatus等于-1
                if (ws == Node.SIGNAL) {
                    //CAS将头节点的waitStatus修改为0,如果失败,不执行后面代码,继续for循环,直到修改成功,然后唤醒头节点的后继节点
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                //如果头节点的waitStatus等于0并且CAS将waitStatus的值修改为-3失败,则不再执行下面的代码,继续for循环,直到修改成功
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            //第一次for循环唤醒同步队列头节点的后继节点,后继节点获取到锁后,这里if返回false,等第二次for循环,就返回true了
            if (h == head)                   // loop if head changed
                break;
        }
}
//AQS类的方法
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.
         */
        //获取头节点的waitStatus
        int ws = node.waitStatus;
        //如果头节点的waitStatus小于0
        if (ws < 0)
            //设置头节点的waitStatus为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;
        //如果头节点的后继节点为null或取消等待了
        if (s == null || s.waitStatus > 0) {
            s = null;
            //倒序遍历,将同步队列中已经取消等待的节点移除,找到离头节点最近的第一个waitStatus<=0的节点
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        //如果节点不等于null,唤醒节点线程
        if (s != null)
            LockSupport.unpark(s.thread);
}
AQS同步队列

线程3唤醒主线程

主线程获取锁

线程3将state减到0后的AQS同步队列

线程3唤醒主线程后的AQS同步队列

await方法

public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}
//AQS类方法
public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        //如果线程已经被中断,抛出中断异常
        if (Thread.interrupted())
            throw new InterruptedException();
        //如果state不等于0,需要阻塞当前线程
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
}
protected int tryAcquireShared(int acquires) {
    return (getState() == 0) ? 1 : -1;
}
//AQS类方法
//当state不等于0时,才进入该方法
private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        //将当前线程封装成Node,以共享模式放入同步队列末尾(之前的AQS源码文章有分析过,这里不再赘述)
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                //获取当前节点前置节点
                final Node p = node.predecessor();
                //如果前置节点是头节点
                if (p == head) {
                    //(getState() == 0) ? 1 : -1;
                    int r = tryAcquireShared(arg);
                    //如果state不等于0,则继续for循环,否则,进入if代码块
                    if (r >= 0) {
                        //设置当前节点为头节点并唤醒头节点后继节点
                        setHeadAndPropagate(node, r);
                        //移除原头节点
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                //如果当前节点的前置节点不是头结点,执行if
                //挂起当前线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
}
//AQS类的方法
//state等于0才进入该方法
private void setHeadAndPropagate(Node node, int propagate) {
        //获取同步队列头节点
        Node h = head; // Record old head for check below
        //设置当前节点为head,且当前节点的thread和prev都置为null
        setHead(node);
        /*
         * Try to signal next queued node if:
         *   Propagation was indicated by caller,
         *     or was recorded (as h.waitStatus either before
         *     or after setHead) by a previous operation
         *     (note: this uses sign-check of waitStatus because
         *      PROPAGATE status may transition to SIGNAL.)
         * and
         *   The next node is waiting in shared mode,
         *     or we don't know, because it appears null
         *
         * The conservatism in both of these checks may cause
         * unnecessary wake-ups, but only when there are multiple
         * racing acquires/releases, so most need signals now or soon
         * anyway.
         */
        //这里propagate == 1
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            //获取当前节点的后继节点
            Node s = node.next;
            //后继节点为空或者为shared
            if (s == null || s.isShared())
                //释放共享锁,唤醒头节点后面的线程
                doReleaseShared();
        }
}

总结

新建一个CountDownLatch,构造器传入初始化state值,调用一次countDown方法,state减1,在调用await方法时,如果state不等于0,则当前线程阻塞,只有state等于0时,当前线程才能继续执行。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容