代码语言:javascript复制
1 package com.thread.test.thread;
2
3 import java.util.Random;
4 import java.util.concurrent.*;
5
6 /**
7 * CyclicBarrier
8 * 同步工具:允许一组线程共同等待一个壁垒点
9 * 适用于固定数量线程的同步
10 * 等待线程释放后可以重复使用
11 *
12 * Created by windwant on 2016/5/27.
13 */
14 public class MyCyclicBarrier {
15 public static void main(String[] args) {
16 ExecutorService es = Executors.newCachedThreadPool();
17 CyclicBarrier cb = new CyclicBarrier(5, new MainTask());//MainTask可选
18 Random r = new Random();
19 es.execute(new SubTask(cb, r.nextInt(10), "task1"));
20 es.execute(new SubTask(cb, r.nextInt(10), "task2"));
21 es.execute(new SubTask(cb, r.nextInt(10), "task3"));
22 es.execute(new SubTask(cb, r.nextInt(10), "task4"));
23 es.execute(new SubTask(cb, r.nextInt(10), "task5"));
24 es.shutdown();
25 }
26 }
27
28 class MainTask implements Runnable {
29
30 public void run() {
31 try {
32 System.out.println("mian task begin");
33 for (int i = 0; i < 5; i ) {
34 Thread.sleep(1000);
35 System.out.println("============" i "============");
36 }
37 System.out.println("mian task implemented");
38 } catch (Exception e) {
39 e.printStackTrace();
40 }
41
42 }
43 }
44
45 class SubTask implements Runnable{
46
47 private CyclicBarrier cb;
48
49 private int seconds;
50
51 private String taskName;
52
53 SubTask(CyclicBarrier cb, int seconds, String taskName){
54 this.cb = cb;
55 this.seconds = seconds;
56 this.taskName = taskName;
57 }
58
59 public void run() {
60 try{
61 System.out.println("subtask " taskName " begin, need time: " seconds "s");
62 long b = System.currentTimeMillis();
63 for (int i = 0; i < seconds; i ) {
64 Thread.sleep(1000);
65 System.out.println("subtask: " taskName "============" i "============");
66 }
67 long d = System.currentTimeMillis() - b;
68 System.out.println("subtask " taskName " over, executing time: " TimeUnit.SECONDS.convert(d, TimeUnit.MILLISECONDS));
69 cb.await();
70 } catch (InterruptedException e) {
71 e.printStackTrace();
72 } catch (BrokenBarrierException e) {
73 e.printStackTrace();
74 }
75 }
76 }
项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo