package com.my.demo;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 用CountDownLatch来模拟运动员赛跑的Demmo.
*/
public class CountDownLatchDemo {
/** 参与比赛的人数(并发线程数) */
private static int PLAYER_NUM = 8;
public static void main(String[] args) throws Exception {
//用于让主线程(裁判)等待所有子线程(运动员)就绪
final CountDownLatch readySignal = new CountDownLatch(PLAYER_NUM);
//用于让子线程(运动员)等待主线程(裁判)发号施令
final CountDownLatch beginSignal = new CountDownLatch(1);
//用于让主线程(裁判)等待所有子线程(运动员)执行(比赛)完成
final CountDownLatch endSignal = new CountDownLatch(PLAYER_NUM);
ExecutorService executorService = Executors.newFixedThreadPool(PLAYER_NUM);
for(int i = 0; i < PLAYER_NUM; i++){
final int num = i + 1;
Runnable player = new Runnable(){
@Override
public void run() {
System.out.println("No." + num + " is ready");
//一个任务就绪后,减少readySignal上的等待
readySignal.countDown();
try {
//等待主线程比赛开始的命令
beginSignal.await();
System.out.println("No." + num + " is running");
Thread.sleep((long) (Math.random() * 5000));
System.out.println("No.-----" + num + " arrived");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//每个线程执行完成后,调用countDown减少在endSignal上的等待线程数
endSignal.countDown();
}
}
};
executorService.execute(player);
}
//这里让主线程等待,确保所有子线程已开始执行并调用了await进入等待状态
readySignal.await();
System.out.println("Game Start!");
//所有等待在beginSignal上的线程(运动员)开始执行(比赛)
beginSignal.countDown();
try {
//等待所有在endSignal上的线程(运动员)执行(比赛)完成
endSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Game Over!");
executorService.shutdown();
}
}
}
CounDownLatchDemo
点赞
收藏