有10个线程, 主线程怎么等待10个线程执行完之后才执行

时间:2021-06-10 17:37:56   收藏:0   阅读:0

 

 

测试代码如下:

public class ThreadWait {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exector = Executors.newFixedThreadPool(5);
        int threadNumber = 13;
        final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            final int threadID = i;
            exector.execute(
                    () -> {
                        try {
                            Thread.sleep(2000);
                            System.out.println(String.format("threadID:[%s] finished!!", threadID));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            countDownLatch.countDown();  //这个不管是否异常都需要数量减,否则会被堵塞无法结束
                        }
                    }
            );
        }
        countDownLatch.await();//保证之前的所有的线程都执行完成,才会走下面的
        System.out.println(countDownLatch.getCount());
        System.out.println("main thread finished!!");
    }
}
结果为:

threadID:[0]finished!!
        threadID:[1]finished!!
        threadID:[4]finished!!
        threadID:[3]finished!!
        threadID:[2]finished!!
        threadID:[9]finished!!
        threadID:[8]finished!!
        threadID:[5]finished!!
        threadID:[6]finished!!
        threadID:[7]finished!!
        threadID:[10]finished!!
        threadID:[11]finished!!
        threadID:[12]finished!!
        0
        main thread finished!!

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!