CountDownLatch
介绍
CountDownLatch是一个计数器闭锁,通过它可以完成类似于阻塞当前线程的功能。CountDownLatch 用一个计数器进行初始化,线程调用await
函数等待 CountDownLatch的计数器减为0后,才能继续执行。而计数器如何减为0呢?其他线程通过调用countDown
函数,减少计数器。
代码
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);
}
打印信息
从打印信息看到
finish
是在threadNum
变为0之后才打印的。