/** * Decrements the count of the latch, releasing all waiting threads if * the count reaches zero. * * <p>If the current count is greater than zero then it is decremented. * If the new count is zero then all waiting threads are re-enabled for * thread scheduling purposes. * * <p>If the current count equals zero then nothing happens. */ publicvoidcountDown(){ sync.releaseShared(1); // 释放一个资源 } publicfinalbooleanreleaseShared(int arg){ if (tryReleaseShared(arg)) { doReleaseShared();// doReleaseShared会唤醒同步队列中阻塞挂起的线程 returntrue; } returnfalse; } // 重写了AQS中的方法:尝试释放共享资源 protectedbooleantryReleaseShared(int releases){ // Decrement count; signal when transition to zero for (;;) { int c = getState(); if (c == 0) returnfalse; int nextc = c-1; // CAS减少count if (compareAndSetState(c, nextc)) return nextc == 0; // 当检测到状态值为0时,通知同步队列中被挂起的线程 } }