使用CountDownLatch让主线程等待子线程全部结束后再关闭线程池

public static void main(String[] args) throws Exception {
    int n = 3;
    String[] tasks = {"发短信完毕", "发微信完毕", "发QQ完毕"};
    int[] executeTimes = new int[]{2, 5, 1};
    CountDownLatch countDownLatch = new CountDownLatch(n);
    ExecutorService executorService = Executors.newFixedThreadPool(n);

    long start = System.currentTimeMillis();
    for (int i = 0; i < n; i++) {
        int finalI = i;
        executorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(executeTimes[finalI]);
                System.out.println(tasks[finalI]);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        });
    }
    countDownLatch.await();
    System.out.println("所有消息都发送完毕了,继续执行主线程任务。\n耗时ms:" + (System.currentTimeMillis() - start));
    // 不要忘记关闭线程池,不然会导致主线程阻塞无法退出
    executorService.shutdown();
}

  

posted @ 2025-04-03 16:15  球你嘞~  阅读(13)  评论(0)    收藏  举报