CountDownLatch
和CyclicBarrier的区别是,CyclicBarrier可以循环使用,CountDownLatch不可以;CyclicBarrier可以有一个Runnable参数,在所有子任务执行完成后触发一个动作。两者在模型上近似,都是等待一批固定数量的子任务执行完成后才能执行主任务。
流程如下:
示例代码如下:
@Test public void test3() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(5); ExecutorService executorService = Executors.newCachedThreadPool(); for(int i = 0; i < 5; i++) { executorService.execute(new Task(countDownLatch)); } countDownLatch.await(); executorService.shutdown(); } public static class Task implements Runnable { CountDownLatch countDownLatch; public Task(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { System.err.println("当前完成的任务数目:" + countDownLatch.getCount()); countDownLatch.countDown(); } }