目录
CountDownLatch允许一个或多个线程等待其他线程完成操作,基于对共享锁的获取来实现,获取到共享锁,说明线程不再需要等待,未获取到,说明线程仍然需要等待。
成员变量
private final Sync sync; // 用来实现功能的基础组件,继承AQS,Sync是CountDownLatch的静态内部类
构造方法
// count表示需要countDown方法调用的次数
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
线程等待
// 线程等待
public void await() throws InterruptedException {
// 通过获取共享锁实现,获取不成功则等待
sync.acquireSharedInterruptibly(1);
}
// 线程超时等待
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
// 通过获取共享锁实现
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
线程等待方法会调用到Sync的tryAcquireShared方法。
// 尝试获取共享锁
protected int tryAcquireShared(int acquires) {
// 当getState()为0时,则获取共享锁成功,不为0则获取共享锁不成功
// getState()初始值为count
return (getState() == 0) ? 1 : -1;
}
countDown方法
// 将AQS的state数值减少一
public void countDown() {
// 通过释放共享锁实现
sync.releaseShared(1);
}
countDown方法通过释放共享锁来实现,内部会调用到Sync的tryReleaseShared方法。
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0) // 为0则不用处理
return false;
int nextc = c - 1;
if (compareAndSetState(c, nextc)) // CAS操作确保state减少1
return nextc == 0;
}
}
getCount方法
// 仍然需要countDown方法执行的次数
public long getCount() {
return sync.getCount();
}
getCount方法是线程还需要等待countDown方法执行的次数。
版权声明:本文为For_Forever原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。