juc同时起跑问题

之前面试遇到的问题:
如何保证多个线程同时起跑问题,并统计最后结束比赛用时

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(); }
    原文作者:JUC
    原文地址: https://blog.csdn.net/qq_36752632/article/details/81127704
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞