Java并发之CountDownLatch 多功能同步工具类

 1 package com.thread.test.thread;
 2 
 3 import java.util.Random;
 4 import java.util.concurrent.*;
 5 
 6 /**
 7  * CountDownLatch
 8  * 同步策略 允许一个或多个线程等待一些列其它线程操作完成后执行
 9  * 由给定count初始化
10  * await方法等待所有等待线程countDown方法执行之后释放
11  * count不能重置,只能使用一次 对比CyclicBarrier
12  * 多用途同步工具:
13  * 初始化为1的CountDownLatch可以作为 on/off开关;所有线程等待直到所有线程都执行了countDown gate效果
14  * 初始化为N....
15  *
16  * 必须等待所有线程都执行完成后才能让所有线程继续执行时其比较有用的特性
17  *
18  * Created by windwant on 2016/5/27.
19  */
20 public class MyCountDownLatch {
21 
22     public static void main(String[] args) throws InterruptedException {
23         ExecutorService es = Executors.newCachedThreadPool();
24         CountDownLatch cd = new CountDownLatch(5);
25         Random r = new Random();
26         es.execute(new SubWork(cd, r.nextInt(10), "task1"));
27         es.execute(new SubWork(cd, r.nextInt(10), "task2"));
28         es.execute(new SubWork(cd, r.nextInt(10), "task3"));
29         es.execute(new SubWork(cd, r.nextInt(10), "task4"));
30         es.execute(new SubWork(cd, r.nextInt(10), "task5"));
31         cd.await();
32         es.execute(new MainWork());
33         es.shutdown();
34     }
35 
36 
37 }
38 
39 class MainWork implements Runnable {
40 
41     public void run() {
42         try {
43             System.out.println("mian task begin");
44             for (int i = 0; i < 5; i++) {
45                 Thread.sleep(1000);
46                 System.out.println("============" + i + "============");
47             }
48             System.out.println("mian task implemented");
49         } catch (Exception e) {
50             e.printStackTrace();
51         }
52     }
53 }
54 
55 class SubWork implements Runnable{
56 
57     private CountDownLatch cd;
58 
59     private int seconds;
60 
61     private String taskName;
62 
63     SubWork(CountDownLatch cd, int seconds, String taskName){
64         this.cd = cd;
65         this.seconds = seconds;
66         this.taskName = taskName;
67     }
68 
69     public void run() {
70         try{
71             System.out.println("subwork " + taskName + " begin, need time: " + seconds + "s");
72             long b = System.currentTimeMillis();
73             for (int i = 0; i < seconds; i++) {
74                 Thread.sleep(1000);
75                 System.out.println("subtask: " + taskName + "============" + i + "============");
76             }
77             long d = System.currentTimeMillis() - b;
78             System.out.println("subwork " + taskName + " over, executing time: " + TimeUnit.SECONDS.convert(d, TimeUnit.MILLISECONDS));
79             cd.countDown();
80         } catch (InterruptedException e) {
81             e.printStackTrace();
82         }
83     }
84 }

项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo

posted @ 2016-10-21 16:24  WindWant  阅读(337)  评论(0编辑  收藏  举报
文章精选列表