1.类声明:
//需要等待某个条件完成,即等待其他某些线程完成操作,才能继续执行的时候,可以使用此类。在计数器到达0之前,await方法会一直阻塞
public class CountDownLatch{}
2.变量:
//同步器
private final Sync sync;
3.方法:
//初始化
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
//自定义队列同步器,控制并发的访问
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;
}
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
//当前线程等待,知道计数器变为0
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//某个线程调用,计数器-1
public void countDown() {
sync.releaseShared(1);
}