//Allow one or more threads to wait for the internal AQS before completing a set of operations 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; } } } // first look at the constructor public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); //Initialize sync. this.sync = new Sync(count); } // block the current thread public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } //Block the specified time timeout and return false public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } //Decrement count.0 to wake up all waiting threads. public void countDown() { sync.releaseShared(1); } //Get the current counter count public long getCount() { return sync.getCount(); } public String toString() { return super.toString() + "[Count = " + sync.getCount() + "]"; }
Read CountDownLatch source code
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326449464&siteId=291194637
Recommended
Ranking