1、CountDownLatch,主要用于将一个任务分为n个独立的部分,等这些部分都完成后继续接下来的任务,CountDownLatch 只能出发一次,计数值不能被重置。一个或者是一部分线程 ,等待另外一部线程都完成了,再继续执行
例子:
Module:一个工程中各子模块的任务执行
- public class Module implements Runnable {
- private CountDownLatch countDownLatch;
- private String moduleName;
- private int time;
-
-
-
-
-
-
- public Module(CountDownLatch countDownLatch, String moduleName, int time) {
- super();
- this.countDownLatch = countDownLatch;
- this.moduleName = moduleName;
- this.time = time;
- }
-
-
-
-
-
- public void run() {
- work();
- countDownLatch.countDown();
- }
-
-
-
-
- private void work() {
- try {
- TimeUnit.MILLISECONDS.sleep(time);
- System.out.println(moduleName + " 耗时: " + time + "ms.");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- }
-
- }
在整个工程来看,所有的子模块完成之后才能叫完成。处于多模块完结的下游任务。
- public class Controller implements Runnable {
- private CountDownLatch countDownLatch;
-
-
-
-
- public Controller(CountDownLatch countDownLatch) {
- super();
- this.countDownLatch = countDownLatch;
- }
-
-
-
-
-
- public void run() {
- try {
- countDownLatch.await();
- System.out.println("所有模块完成,任务完成");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- }
测试:
- private static final int SIZE = 20;
-
- public static void main(String[] args) {
- CountDownLatch countDownLatch = new CountDownLatch(SIZE);
- Random random = new Random();
- ExecutorService executorService = Executors.newCachedThreadPool();
- Controller controller = new Controller(countDownLatch);
- executorService.execute(controller);
- for (int i = 0; i < SIZE; i++) {
- executorService.execute(new Module(countDownLatch, "模块:" + i, random.nextInt(2000)));
- }
- executorService.shutdown();
-
- }
测试结果:
- 模块:6 耗时: 14ms.
- 模块:13 耗时: 203ms.
- 模块:17 耗时: 339ms.
- 模块:14 耗时: 544ms.
- 模块:3 耗时: 577ms.
- 模块:8 耗时: 580ms.
- 模块:0 耗时: 695ms.
- 模块:12 耗时: 985ms.
- 模块:4 耗时: 1142ms.
- 模块:16 耗时: 1228ms.
- 模块:2 耗时: 1260ms.
- 模块:15 耗时: 1304ms.
- 模块:11 耗时: 1486ms.
- 模块:19 耗时: 1495ms.
- 模块:5 耗时: 1497ms.
- 模块:18 耗时: 1540ms.
- 模块:7 耗时: 1613ms.
- 模块:10 耗时: 1649ms.
- 模块:1 耗时: 1697ms.
- 模块:9 耗时: 1872ms.
- 所有模块完成,任务完成
2、CyclicBarrier: 所有线程互相等待完成。
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/790019,如需转载请自行联系原作者