在并發(fā)工具類中,我們簡單了解了CountDownLatch,接下來走讀下代碼看看其是如何實現(xiàn)的,代碼基于JDK1.7。
代碼走讀
當(dāng)你打開CountDownLatch類后,你會發(fā)現(xiàn)這個類很簡單的,其實就是基于AQS實現(xiàn)的共享鎖。然后重寫了tryAcquireShared()、tryReleaseShared()方法。AQS中定義了個模板方法,獲取鎖和釋放鎖的流程都一樣,這里不再贅述,具體大家請參考AQS源碼走讀。

CountDownLatch其實就是對于計數(shù)器進(jìn)行加減操作
CountDownLatch調(diào)用await()方法獲取共享鎖,當(dāng)計數(shù)器為0是獲取到鎖,計數(shù)器初始的值通過構(gòu)造方法傳入。
CountDownLatch調(diào)用countDown()方法釋放共享鎖,計數(shù)器減1。
總結(jié):CountDownLatch基于AQS共享鎖實現(xiàn),其最核心的就是其中的計數(shù)器,調(diào)用countDown()方法計數(shù)器減1,當(dāng)計數(shù)器為0時等待的線程獲取到鎖。
例子
public class CountDownLatchDemo {
private static int LATCH_SIZE = 5;
private static CountDownLatch doneSignal;
public static void main(String[] args) {
try {
doneSignal = new CountDownLatch(LATCH_SIZE);
// 新建5個任務(wù)
for (int i = 0; i < LATCH_SIZE; i++)
new InnerThread().start();
System.out.println("main await begin.");
// "主線程"等待線程池中5個任務(wù)的完成
doneSignal.await();
System.out.println("main await finished.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class InnerThread extends Thread {
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " sleep 1000ms.");
// 將CountDownLatch的數(shù)值減1
doneSignal.countDown();
doneSignal.await();
System.out.println("11111111111");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}