package com.wenfengkeji.thread.zhangxiaoxiang;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
*需求:
* 模拟10个运动员赛跑,比赛的进场,到达起跑线,起跑,并记录运动员的成绩。
* 要求:
* 当所有运动员准备就绪,裁判发出比赛开始号令枪,运动员开始起跑,当所有运动员到达目的地,裁判宣布比赛结束。
* 运动员在逻辑上必须是同时起跑,就是说不能抢跑
* 目的:复习一下多线程
*/
public class Demo {
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
int athleteNums = 10;
final CountDownLatch cdl_to_boss = new CountDownLatch(1); //当运动员处在同一起跑后告诉裁判可以开始发枪了
final CountDownLatch cdl_to_begin = new CountDownLatch(1); //当裁判员收到运动员准备就绪的命令后
final CountDownLatch cdl_answer = new CountDownLatch(athleteNums);
final CyclicBarrier cb = new CyclicBarrier(athleteNums); //控制运动员是同一时刻出发的,没有抢跑
for(int i = 0; i < athleteNums; i++)
{
es.execute(new Runnable(){
public void run()
{
try {
Thread.currentThread().sleep((long)(Math.random() * 10000)); //模拟运动陆续进场到起跑线
System.out.println(Thread.currentThread() + "到达起跑线,准备完毕等待发令枪响"); //到达起跑线,准备完毕等待发令枪响
cb.await(); //继续等待其他 运动员就绪
cdl_to_boss.countDown(); //告诉裁判所有运动准备就绪
cdl_to_begin.await(); //当裁判发令枪响后 才开始跑 发令枪响前都处于等待状态
long start = System.currentTimeMillis();
System.out.println(Thread.currentThread() + "开始起跑");
Thread.currentThread().sleep((long)(Math.random() * 10000));
long end = System.currentTimeMillis();
System.out.println(Thread.currentThread() + "到达终点" + "成绩:" + (end - start) + "ms");
cdl_answer.countDown(); //告诉裁判有一个运动员已经到达终点了
} catch (Exception e) {
}
}
});
}
try{
cdl_to_boss.await();
System.out.println("裁判发出起跑令:");
cdl_to_begin.countDown();
cdl_answer.await();
System.out.println("所有运动员到达终点,裁判宣布比赛结束.");
}catch(Exception e)
{
throw new RuntimeException(e);
}
}
}
|