首页 新闻 会员 周边

关于下面CountDownLatch代码段的疑问

0
悬赏园豆:10 [已解决问题] 解决于 2019-02-14 15:01
public class CountDownLatchExample1 {

    private static int threadCount = 10;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int count = i;
            es.execute(() -> {
                try {
                    test(count);
                } catch (Exception e) {
                    log.error("Exception,{}", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await(1, TimeUnit.MILLISECONDS);
        log.info("======");
        es.shutdown();
    }

    public static void test(int i) throws InterruptedException {
        Thread.sleep(1000);//此方法延迟1秒再执行
        log.info("test {}", i);
    }

}

由于在方法里面加了一秒延迟 所以先打印出======,那为什么其他10条log信息同一秒出现了?

 

JaneEyreWork的主页 JaneEyreWork | 初学一级 | 园豆:11
提问于:2019-02-14 11:44
< >
分享
最佳答案
0

你这是线程池,一下子跑十次,所有test方法一下子就全输出了。

收获园豆:10
让我发会呆 | 老鸟四级 |园豆:2929 | 2019-02-14 12:55
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册