之前面试遇到的问题:
如何保证多个线程同时起跑问题,并统计最后结束比赛用时
public static void dealByCircle() throws Exception {
CyclicBarrier barrier=new CyclicBarrier(3);
CountDownLatch latch=new CountDownLatch(2);
ExecutorService service=Executors.newFixedThreadPool(2);
Data data=new Data();
service.execute(()->{
try {
Thread.sleep(5000);
System.out.println("player1 ready");
barrier.await();
System.out.println("player1 start run");
Thread.sleep(2000);
System.out.println("player1 end");
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
});
service.execute(()->{
try {
Thread.sleep(3000);
System.out.println("player2 ready");
barrier.await();
System.out.println("player2 start run");
Thread.sleep(3000);
System.out.println("player2 end");
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
});
barrier.await();
Long Starttime=new Date().getTime();
System.out.println("start run !times:"+Starttime);
latch.await();
Long endtime=new Date().getTime();
System.out.println("complete run !times:"+endtime);
System.out.println("total match time:"+((endtime-Starttime)/1000) +"second");
service.shutdown();
}