CountDownLatch

CountDownLatch.png

Constructor

public CountDownLatch(int count) {
    if (count < 0) throw new IllegalArgumentException("count < 0");
    // 可以看到CountDownLatch的资源数其实就是Sync的state而已,之后的操作就是围绕这个计数展开
    this.sync = new Sync(count);
}

Sync(int count) {
    setState(count);
}

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) {
    // 其实就是state自减,一直归零为止
    for (;;) {
        int c = getState();
        if (c == 0)
            return false;
        int nextc = c-1;
        if (compareAndSetState(c, nextc))
            return nextc == 0;
    }
}

await

public void await() throws InterruptedException {
    // AQS托管,也就是当state归零,那么await就结束返回
    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) {
    // 取得共享锁的条件是state归零
    // 否则说明释放的资源还没有回收完毕,那么会,等待上面countdown来唤醒
    return (getState() == 0) ? 1 : -1;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容