Runner.java
package com.source.current;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Runner implements Callable<Integer> {
private CountDownLatch begin; //裁判
private CountDownLatch end; //运动员
public Runner(CountDownLatch begin, CountDownLatch end) {
super();
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int score= new Random().nextInt(10);
//裁判等待运动员上场
begin.await();
TimeUnit.MILLISECONDS.sleep(score);
// 运动员计数
end.countDown();
return score;
}
}
RunnerImpl.java
package com.source.current;
import java.util.ArrayList;
import java.util.concurrent.*;
public class RunnerImpl {
public static void main(String[] args) throws Exception {
int person = 8;
CountDownLatch begin=new CountDownLatch(1); // 裁判
CountDownLatch end = new CountDownLatch(8); // 运动员
ExecutorService executorService = Executors.newFixedThreadPool(person);
ArrayList<Future<Integer>> list = new ArrayList<Future<Integer>>();
for (int i = 0; i < person; i++) {
list.add(executorService.submit(new Runner(begin,end)));
}
//枪声响起
begin.countDown();
//等待所有运动员跑完
end.await();
int count =0;
int highScore=0;
for (Future<Integer> f:list) {
count+=f.get();
if(f.get()>highScore){
highScore=f.get();
}
}
System.out.println("运动员人数为:"+person+"总分为:"+count+"平均分为:"+count/person+"最高分为:"+highScore);
executorService.shutdown();
}
}
运动员人数为:8总分为:38平均分为:4最高分为:9