CountDownLatch 源码分析

CountDownLatch 源码分析

await 逻辑

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

Sync 的方法

// 获取共享锁,只有state==0 才成功获取锁,否则都需要等待
protected int tryAcquireShared(int acquires) {
    return (getState() == 0) ? 1 : -1;
}

countDown逻辑

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

Sync 类的方法

protected boolean tryReleaseShared(int releases) {
    for (;;) {
        int c = getState();
        if (c == 0)
            return false;
        int nextc = c-1;
        if (compareAndSetState(c, nextc))
            // 只有状态等于0,才能唤醒等待队列中节点
            return nextc == 0;
    }
}

总结

CountDownLatch的实现也比较简单,利用AQS的共享锁来实现的,如果state==0,才能 await成功,否则需要等待。

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

推荐阅读更多精彩内容