1 import java.time.Instant;
2 import java.util.concurrent.*;
3
4 public class Demo_CyclicBarrier_CountDownLatch
5 {
6 private static final int COUNT_WORKER = 2;
7
8 public static void main(String[] args) throws InterruptedException
9 {
10 CountDownLatch countDownLatch = new CountDownLatch(COUNT_WORKER);
11 CyclicBarrier cyclicBarrier = new CyclicBarrier(COUNT_WORKER, () -> {
12 System.out.println("准备开始联调吧...");
13 lastSecond(3L);
14 });
15
16 ExecutorService executorService = Executors.newFixedThreadPool(2);
17 executorService.execute(new Coder(10L, "后端", countDownLatch, cyclicBarrier));
18 executorService.execute(new Coder(3L, "前端", countDownLatch, cyclicBarrier));
19
20 countDownLatch.await();
21 System.out.println("开发联调结束,需求交付...");
22 }
23
24 /**
25 * 线程持续second秒
26 */
27 private static void lastSecond(long second)
28 {
29 Instant instant = Instant.now();
30 while (Instant.now().minusSeconds(second).isBefore(instant))
31 {
32 }
33 }
34
35 static class Coder implements Runnable
36 {
37 // 开发联调时间
38 private long workTime;
39
40 private String name;
41
42 private CountDownLatch countDownLatch;
43
44 private CyclicBarrier cyclicBarrier;
45
46 public Coder(long workTime, String name, CountDownLatch countDownLatch, CyclicBarrier cyclicBarrier)
47 {
48 this.workTime = workTime;
49 this.name = name;
50 this.countDownLatch = countDownLatch;
51 this.cyclicBarrier = cyclicBarrier;
52 }
53
54 @Override
55 public void run()
56 {
57 try
58 {
59 System.out.println(this.name + " are coding...");
60 lastSecond(this.workTime);
61 System.out.println(this.name + " code end wait debugging..");
62
63 this.cyclicBarrier.await();
64
65 System.out.println(this.name + " are debugging..");
66 lastSecond(this.workTime);
67
68 System.out.println(this.name + " debug end..");
69 this.countDownLatch.countDown();
70 }
71 catch (Exception e)
72 {
73 e.printStackTrace();
74 }
75 }
76 }
77 }