线程池等待所有线程结束

本文介绍了两种在Java中确保线程池中所有任务执行完毕的方法,包括详细步骤和代码示例,帮助理解多线程环境下如何有效控制线程执行的顺序和同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一

		ArrayList<Integer> integers = new ArrayList<>();
        ThreadPoolExecutor executor = ThreadPoolUtils.init();
        for (int i = 0; i < 10; i++) {
            executor.execute(new Add(i, integers));
        }
        if(!executor.isShutdown()){
            executor.shutdown();
        }
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
        }
        System.out.println(integers+"----------------");
    

方法二

CountDownLatch latch = new CountDownLatch(fileList.size());
        // 计算机cpu核心数
        int processors = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor executor = ThreadPoolUtils.init(processors*2, processors*5, 10L, TimeUnit.SECONDS,
                fileList.size());
        for (int i = 0; i < fileList.size(); i++) {
            int finalI = i;
            executor.execute(() -> {
                do();
                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!executor.isShutdown()){
            executor.shutdown();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值