ThreadPoolExecutor,ForkJoinPool线程池 等待所有线程都完成后再返回数据

本文介绍了如何使用ThreadPoolExecutor实现线程池并发处理,以及ForkJoinPool在Java 8中的应用,重点讲解了任务批处理和自定义线程数。通过实例演示了如何等待所有任务完成后返回结果,并探讨了两者在性能优化中的作用。

线程池使用方法记录

使用线程池ThreadPoolExecutor,ForkJoinPool 等待所有线程都完成后再返回数据

ThreadPoolExecutor 具体代码

    public List<GoodsPriceDTO> getGoodPrice(List<SkuPageNo> skuPageNoList) {
        ArrayList<GoodsPriceDTO> goodsPriceDTOS = new ArrayList<>();
        //第三方接口最多同时查100条数据,因此按数量100分批次
        int size = skuPageNoList.size();
        int count = (100+  size - 1)/100;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,16,60,TimeUnit.SECONDS,new LinkedBlockingQueue<>(),new ThreadPoolExecutor.CallerRunsPolicy());
        for (int i = 0; i < count; i++) {
            String skuString = skuPageNoList.subList(i * 100, (Math.min((i + 1) * 100, size))).stream().map(SkuPageNo::getSkuNo).map(String::valueOf).collect(Collectors.joining(","));
            executor.submit(()->{//具体业务代码});}
        executor.shutdown();
        try {
        //当shutdown()请求发送后, 要求等待所有线程都完成 任务后才能关闭线程
                    executor.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return goodsPriceDTOS;
    }

ForkJoinPool 具体代码

java8 中parallelStream使用了ForkJoinPool 线程池,默认的核心线程数等于CPU的核数

        //通过这两种方法可以自己设置线程数
        //方法一
        int numTasks = 10;
        ForkJoinPool pool = new ForkJoinPool(numTasks);
        //方法二
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "10");

parallelStream中 使用自定义的线程数

 List<GoodsSKUDTO> jdGoodsDTOList = Collections.synchronizedList(new ArrayList<>());
        //System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "9");
        int numTasks = 10;
        ForkJoinPool pool = new ForkJoinPool(numTasks);
        //System.out.println("getCustomParallelism=" +pool.getParallelism());
        pool.submit(() -> skuPageNoList.parallelStream().filter(Objects::nonNull).forEach(skuPageNo -> {/具体业务逻辑
        }));
        pool.shutdown();
        try {
            pool.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return jdGoodsDTOList;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值