java并发编程之CountDownLatch

时间:2022-05-09 16:42:53

简介

CountDownLatch 犹如倒计时计数器,countDown()计数器建议1,当等于0时所有等待者任务开始进行,可用于实现 一对多的指令通知场景,例如运动员赛跑的场景

java并发编程之CountDownLatchjava并发编程之CountDownLatch
 1 public class MyThreadCountDownLatch {
2
3 public static void main(String[] args) {
4 ExecutorService threadPool = Executors.newCachedThreadPool();
5 final CountDownLatch mainCdl = new CountDownLatch(1);//主裁判计数器(指令发射器)
6 final CountDownLatch taskCdl = new CountDownLatch(3);//运动员计数器(结果反馈)
7 for(int i=1;i<=3;i++){ //创建三个线程,模拟三个运动员
8 Runnable task=new Runnable() {
9
10 @Override
11 public void run() {
12 try {
13 String threadName=Thread.currentThread().getName();
14 System.out.println("线程"+threadName +"准备接受指令");
15 mainCdl.await();
16 System.out.println("线程"+threadName +"收到指令");
17 Thread.sleep((long) (Math.random()*10000)); //真实以实际业务代码准
18 System.out.println("线程"+threadName +"回应处理结果");
19 taskCdl.countDown();//子线程发送结果指令(子线程计数器减1)
20 } catch (InterruptedException e) {
21 e.printStackTrace();
22 }
23 }
24 };
25 threadPool.execute(task); //启动线程
26 }
27
28 try {
29 System.out.println("线程"+Thread.currentThread().getName() +"准备发送指令");
30 Thread.sleep((long) (Math.random()*10000));
31 mainCdl.countDown(); //主线发送信号(主线程计数器减1)
32 System.out.println("线程"+Thread.currentThread().getName() +"等待处理结果");
33 taskCdl.await();
34 System.out.println("线程"+Thread.currentThread().getName() +"收到处理结果");
35 } catch (InterruptedException e) {
36 e.printStackTrace();
37 }
38 threadPool.shutdown();
39
40 }
41
42 }
View Code