/** * A synchronization aid that allows one or more threads to wait until * a set of operations being performed in other threads completes. */ publicclassCountDownLatch { //静态内部类实现AQS模板 privatestaticfinalclassSyncextendsAbstractQueuedSynchronizer { privatestaticfinallongserialVersionUID=4982264981922014374L;
protectedbooleantryReleaseShared(int releases) { // Decrement count; signal when transition to zero //CAS实现的释放锁过程 for (;;) { intc= getState(); if (c == 0) returnfalse; intnextc= c-1; if (compareAndSetState(c, nextc)) returnnextc== 0; } } }
/* * Ensure that a release propagates, even if there are other * in-progress acquires/releases. This proceeds in the usual * way of trying to unparkSuccessor of head if it needs * signal. But if it does not, status is set to PROPAGATE to * ensure that upon release, propagation continues. * Additionally, we must loop in case a new node is added * while we are doing this. Also, unlike other uses of * unparkSuccessor, we need to know if CAS to reset status * fails, if so rechecking. */