CountDownLatch

构造方法: (还是设置 state 的值!)
( 当state的值为0的时候,才会执行! 否则阻塞!!!)
public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); }
await 方法:
public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }
public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) doAcquireSharedInterruptibly(arg); }
protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; // 如果不是0 就阻塞 }
countDown 方法:
public void countDown() { sync.releaseShared(1); }
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } return false; }
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; // 将state的值减1 if (compareAndSetState(c, nextc)) return nextc == 0; } }
CountDownLatch 的应用场景:
由前面可以看出,当state的值为0的时候,线程才会正常执行,当state大于1的时候,线程进入等待状态!!!
( 开始执行线程前,等待 n 个线程完成任务!!! )
也许会有遗憾,但是不应该在失败之前
浙公网安备 33010602011771号