Java线程池: 等待所有线程执行完成

场景

需要获取多个结果, 并进行运算, 想通过线程池增加结果获取速度, 且所有结果获取后, 可以继续计算并统一返回。

依赖

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1-jre</version>
</dependency>
  • 使用Java8

代码

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class thread {

    public static void main(String[] args) throws InterruptedException {
        // 定义线程名字,方便回溯
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("test-pool-%d").build();
        // 手动创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy());

        // 调用线程池执行任务
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    String test = getTest();
                    list.add(test);
                    System.out.println(test);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("执行线程.." + Thread.currentThread().getName());
            });
        }

        // 所有任务执行完成且等待队列中也无任务关闭线程池
        threadPoolExecutor.shutdown();
        // 阻塞主线程, 直至线程池关闭
        threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);


        System.out.println("========================");
        System.out.println("=======主线程执行完了======");
        System.out.println("========================");

        System.out.println(list);


    }

    static String getTest() throws InterruptedException {
        Random random = new Random();
        int i = random.nextInt(3000);
        Thread.sleep(i);
        return "hello" + i;
    }

}

执行结果

hello281
执行线程..test-pool-2
hello550
执行线程..test-pool-3
hello671
执行线程..test-pool-4
hello1041
执行线程..test-pool-1
hello813
执行线程..test-pool-3
hello981
执行线程..test-pool-1
hello735
执行线程..test-pool-3
hello1622
执行线程..test-pool-4
hello2393
执行线程..test-pool-0
hello2333
执行线程..test-pool-2
========================
=======主线程执行完了======
========================
[hello281, hello550, hello671, hello1041, hello813, hello981, hello735, hello1622, hello2393, hello2333]

Process finished with exit code 0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值