CountDownLatch 源码分析示例,2021Android进阶者的新篇章

CountDownLatch 源码分析示例,2021Android进阶者的新篇章

构造函数内部,初始化一个Sync(count)

//java.util.concurrent.CountDownLatch

public CountDownLatch(int count) {

this.sync = new Sync(count);

}

private static final class Sync extends AbstractQueuedSynchronizer {

Sync(int count) {

//AQS中的state值,充当计数器

setState(count);

}

}

1.图解AQS框架

CountDownLatch 源码分析示例,2021Android进阶者的新篇章

2.AQS内部类Node属性介绍

CountDownLatch 源码分析示例,2021Android进阶者的新篇章

3.countDown()方法里面做了什么?

//java.util.concurrent.CountDownLatch

public void countDown() {

sync.releaseShared(1);

}

//java.util.concurrent.locks.AbstractQueuedSynchronizer

public final boolean releaseShared(int arg) {

//AQS里面的tryReleaseShared需要子类覆写

if (tryReleaseShared(arg)) {

//state为0的时候,去唤醒等待队列中的线程

doReleaseShared();

return true;

}

return false;

}

//java.util.concurrent.CountDownLatch.Sync

protected boolean tryReleaseShared(int releases) {

for (;

上一篇:C++ STL算法 is_partitioned(29)


下一篇:2021-11-27