模拟的是一个游戏玩家匹配的过程
public static void main(String[] args) throws InterruptedException {
int count = 10;
List<Future<Integer>> futures = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(count);
CyclicBarrier cyclicBarrier = new CyclicBarrier(count,()->{
System.out.println(futures.size() +":名玩家匹配完成");
});
for (int i = 0; i < count; i++) {
Future<Integer> future = executorService.submit(() -> {
try {
int seconds = 1 + (new Random().nextInt(4));
TimeUnit.SECONDS.sleep(seconds);
System.out.println(Thread.currentThread().getName() + ":游戏房间已匹配,等待其他玩家加入... ,匹配耗时:"+seconds);
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + ":进入游戏");
return seconds;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
});
futures.add(future);
}
executorService.shutdown();
Integer avgLoading = 0;
for (Future<Integer> future : futures) {
try {
avgLoading += future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
System.out.println("平均加载耗时:" + (double)avgLoading / futures.size());
}