class="java"> //在完成一组操作之前允许一个或多个线程等待内部用的AQS 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; } } } //先看构造函数 public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); //初始化sync. this.sync = new Sync(count); } //阻塞当前线程 public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } //阻塞指定时间超时返回false public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } //递减count.0则唤醒等待的所有线程。 public void countDown() { sync.releaseShared(1); } //获取当前计数器数量 public long getCount() { return sync.getCount(); } public String toString() { return super.toString() + "[Count = " + sync.getCount() + "]"; }