CountDownLatch會接受一個初始化的int值count,通過調用await方法阻塞當前線程。通過其他線程調用countDown來降低當前狀態(tài)值,當當前狀態(tài)將至0 時,所有阻塞在CountDownLatch的線程都會立刻從await返回。
CountDownLatch時一次性的,不可以重置,如果需要重置請使用CyclicBarrier。
實現比較簡單。就是abstractQueuedSynchronizer基礎上的實現。
首先在CountDownLatch內有一個Sync的內部靜態(tài)子類,繼承自AQS。
這里主要是重寫了tryAcquireShared和tryReleaseShared兩個共享鎖。以及一個帶參數的構造器構造器用來初始化count數字。
在
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) {//當當前狀態(tài)為0是可以獲得一個共享鎖。 return (getState() == 0) ? 1 : -1; } protected boolean tryReleaseShared(int releases) {//只要當前線程不是0則循環(huán)嘗試cas降低state直至成功為止。 // 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; } } }每個CountDownLatch包含一個Sync實例。使用組合的形式,將公用方法委托給這個Sync實例實現。
public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); } public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } public void countDown() { sync.releaseShared(1); } public long getCount() { return sync.getCount(); }新聞熱點
疑難解答