CountDownLatch
介紹
CountDownLatch是一個(gè)計(jì)數(shù)器閉鎖乾戏,通過(guò)它可以完成類(lèi)似于阻塞當(dāng)前線程的功能模暗。CountDownLatch 用一個(gè)計(jì)數(shù)器進(jìn)行初始化,線程調(diào)用await
函數(shù)等待 CountDownLatch的計(jì)數(shù)器減為0后欧啤,才能繼續(xù)執(zhí)行睛藻。而計(jì)數(shù)器如何減為0呢?其他線程通過(guò)調(diào)用countDown
函數(shù)邢隧,減少計(jì)數(shù)器店印。
代碼
private void countDownLatchTest() {
TAG = "countDownLatchTest";
ExecutorService executorService = Executors.newCachedThreadPool();
final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
final int threadNum = I;
executorService.execute(new Runnable() {
@Override
public void run() {
try {
RunTest(threadNum);
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
}
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "finish");
executorService.shutdown();
}
private void RunTest(int threadNum) throws Exception {
Thread.sleep(100);
Log.d(TAG, Integer.toString(threadNum));
Thread.sleep(100);
}
打印信息
image.png
從打印信息看到
finish
是在threadNum
變?yōu)?之后才打印的。