import java.util.concurrent.CountDownLatch;
class Aworker implements Runnable {
private int num;
private CountDownLatch begin;
private CountDownLatch end;
public Aworker(int num, final CountDownLatch begin, final CountDownLatch end) {
this.num = num;
this.begin = begin;
this.end = end;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println(num + "th people is ready");
begin.await(); //准备就绪
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
end.countDown(); //计数器减一,到达终点
System.out.println(num + "th people arrive");
}
}
}
public class Race {
public static void main(String[] args) {
int num = 10;
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(num);
for (int i = 1; i <= num; i++) {
new Thread(new Aworker(i, begin, end)).start();
}
try {
Thread.sleep((long) (Math.random() * 5000));
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("judge say : run !");
begin.countDown(); //裁判一声令下开始跑
long startTime = System.nanoTime();
try {
end.await(); //等待结束
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
long endTime = System.nanoTime();
System.out.println("judge say : all arrived !");
System.out.println("spend time: " + (endTime - startTime));
}
}
}
1th people is ready 2th people is ready 4th people is ready 6th people is ready 3th people is ready 10th people is ready 8th people is ready 5th people is ready 7th people is ready 9th people is ready judge say : run ! 1th people arrive 4th people arrive 10th people arrive 5th people arrive 2th people arrive judge say : all arrived ! 9th people arrive 7th people arrive 8th people arrive 3th people arrive 6th people arrive spend time: 970933
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有