跟Semaphore一样,也是通过AQS的共享锁机制实现的,用于一个或多个线程等待其他线程完成的一组操作。原理如下:
1、用AQS的state变量表示操作个数
2、用AQS的共享锁机制完成唤醒
3、等待锁的线程使用acquireShared方法获取共享锁等待
4、操作线程使用releaseShared方法用于唤醒等待共享锁的线程
public class CountDownLatch {
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
//获取共享锁子类实现
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1; //AQS state为0时,获取成功,其他失败
}
//释放共享锁
protected boolean tryReleaseShared(int releases) {
//count递减
for (;;) {
int c = getState();
if (c == 0) //已经为0了,没有可释放的,返回false
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc)) //CAS更新state,为0时唤醒AQS阻塞队列节点
return nextc == 0;
}
}
}
private final Sync sync;
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));
}
public void countDown() {
sync.releaseShared(1);
}
public long getCount() {
return sync.getCount();
}
}