CountDownLatch源码分析

并发源码分析篇:

先来看下CountDownLatch的用法,模拟多线程执行账单计算

public class CountDownLatchDemo {
    static CountDownLatch latch = new CountDownLatch(4);
    static int num = 0;
    public static void main(String[] args) {
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           latch.countDown();
        },"work_1").start();
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           latch.countDown();
        },"work_2").start();
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           latch.countDown();
        },"work_3").start();
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           latch.countDown();
        },"work_4").start();
        try {
            latch.await();
            System.out.println("总结果:"+num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
work_1:我完成+1操作了
work_2:我完成+1操作了
work_3:我完成+1操作了
work_4:我完成+1操作了
总结果:4

在来看下没有用CountDownLatch的效果

public class CountDownLatchDemo {
    static CountDownLatch latch = new CountDownLatch(4);
    static int num = 0;
    public static void main(String[] args) {
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           //latch.countDown();
        },"work_1").start();
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           //latch.countDown();
        },"work_2").start();
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           //latch.countDown();
        },"work_3").start();
        new Thread(() ->{
           num ++;
            System.out.println(Thread.currentThread().getName()+":我完成+1操作了");
           //latch.countDown();
        },"work_4").start();
        try {
            //latch.await();
            System.out.println("总结果:"+num);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
work_1:我完成+1操作了
总结果:1
work_2:我完成+1操作了
work_3:我完成+1操作了
work_4:我完成+1操作了

CountDownLatch的作用显而易见,它能阻塞线程直到达到某个标准后才会被释放继续执行。这个标准就是取决于构造传入的那个值。

现在,我们看下CountDownLatch的底层到底是怎样实现的。
首先就从这个标准说起,看下构造函数做了什么.

    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
    Sync(int count) {
        setState(count);
    }
    protected final void setState(int newState) {
        // 将AQS的state赋值为这个传进来的值
        state = newState;
    }

构造函数就是初始化了AQS中的state值。所以这不在像之前的锁一样,state是0,而是传进来的这个值。

在来看await方法做了什么

    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);
    }
    protected int tryAcquireShared(int acquires) {
         //
          return (getState() == 0) ? 1 : -1;
    }

await方法实际上就是判断state值是否为0,如果为0,啥也不做,如果小于0,线程执行doAcquireSharedInterruptibly方法。所以我们上面主线程调用await方法的时候,只要其他4个线程没有执行完并且调用countDown方法,该state就不会为0,所以肯定会执行doAcquireSharedInterruptibly方法。

    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        // 构建队列
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
               // 当前节点的前一个节点
                final Node p = node.predecessor();
                if (p == head) {
                   // 继续判断state是否为0,为0返回1,否则为-1
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        // 将当前节点设置为头节点并且将节点状态设置为PROPAGATE状态
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                // 将前一个节点的waitstatus状态变为-1并且阻塞当前线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

这里大部分代码都是我们熟悉的,如果不熟悉的,看ReentrantLock源码分析
只有setHeadAndPropagate这个地方不太一样了。稍后我们在来看。
doAcquireSharedInterruptibly方法会继续尝试判断state是否为0,不为0当前线程将阻塞,也就是我们的主线就在此阻塞了。

这时候在来看countDown方法

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

    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }

    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;
            }
        }
    }

这里主要就是tryReleaseShared方法决定,如果为true,执行doReleaseShared,否则什么也不做。
而tryReleaseShared就是获取state并且-1如果为0就会为true,否则就是false。所以这里为ture的时候只有第4个线程执行了countDown方法才会执行后面逻辑。

    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;
            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;
        }
    }

这里跟锁大致一样,唤醒头节点的下一个节点,也就是我们的主线程。所以主线程被唤醒了,继续在挂起的地方执行

    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        // 构建队列
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
               // 当前节点的前一个节点
                final Node p = node.predecessor();
                if (p == head) {
                   // 继续判断state是否为0,为0返回1,否则为-1
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        // 将当前节点设置为头节点并且将节点状态设置为PROPAGATE状态
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                // 将前一个节点的waitstatus状态变为-1并且阻塞当前线程
                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);
        /*
         * 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.
         */
        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() {
        /*
         * 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;
            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;
        }
    }

主线程会执行setHeadAndPropagate,最终又执行到doReleaseShared方法。最终会走if (h == head)跳出了循环,主线程就会继续执行了下面的线程。

其实细心的朋友就会发现,调用countDown的线程也是走这个方法,那为什么只有h == head的时候才能退出循环,如果被唤醒的那个节点先执行了setHead方法,那么head就发生变动了,那么该线程又会循环,于是乎出现了多个线程同时会竞争去唤醒当前head节点的下一个节点,这让我感到很奇怪,为什么不直接让这个线程直接break,唤醒的工作就交给下一个节点就行了,让所有的countDown线程也去抢占释放head节点的下一个节点岂不是更消耗性能,所以一直没能明白这段代码的作用

else if (ws == 0 &&!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue; 
if (h == head)

希望有研究的朋友能讲解下

总结

CountDownLatch实际上就是阻塞线程直到达到了某个标准后,就会被唤醒继续执行。并且这个标准只有在初始化的时候被设置,而CyclicBarrier却有着更丰富的功能,而且这个标准可以reset重置。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355