工具类CountDownLatch的应用---百米赛跑案例

 1 package com.aj.thread;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 import java.util.concurrent.ExecutorService;
 5 import java.util.concurrent.Executors;
 6 
 7 /**
 8  * CountDownLatch的运用,百米赛跑案例
 9  * 
10  * @author yaolei
11  *
12  */
13 public class CountDownLatchTest {
14     public static void main(String[] args) throws InterruptedException {
15         ExecutorService executorService = Executors.newCachedThreadPool();
16         CountDownLatch referee = new CountDownLatch(1);// 裁判
17         CountDownLatch athlete = new CountDownLatch(8);// 运动员
18         Runnable runnable = new Runnable() {
19             @Override
20             public void run() {
21                 try {
22                     // 每一个线程代表一个运动员,运动员们等待裁判发枪
23                     System.out.println(Thread.currentThread().getName() + "准备");
24                     referee.await();// 等待中
25                     Thread.sleep((long) (Math.random() + 10000));// 听到枪声,跑起来吧,飞人们
26                     System.out.println(Thread.currentThread().getName() + "到达终点");
27                     athlete.countDown();
28                 } catch (InterruptedException e) {
29                     // TODO Auto-generated catch block
30                     e.printStackTrace();
31                 }
32 
33             }
34         };
35         // 跑8个线程,代表8个运动员参赛
36         for (int i = 0; i < 8; i++) {
37             executorService.execute(runnable);
38         }
39         executorService.shutdown();
40         // 裁判是主线程,准备发枪
41         Thread.sleep((long) (Math.random() + 10000));
42         // 时间到,发枪
43         referee.countDown();
44         System.out.println("321发枪,开始跑!");
45         System.out.println("裁判准备记录数据:");
46         athlete.await();// 等待运动员跑完
47         System.out.println("所有人跑完,裁判数据记录完毕!,第一名是姚磊哦");
48     }
49 }

猜你喜欢

转载自www.cnblogs.com/iamyaolei/p/9935617.html