CompletableFuture 异步调用,获取返回值

 ExecutorService executor = new ThreadPoolExecutor(
                8, 16, 60,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(100)
        );

        Random random=new Random(10);
        //模拟查询用户列表
        List<User> list=selectUsers();//需要执行的任务列表

        // 任务列表
        List<CompletableFuture<User>> fList = new ArrayList<>();
        list.forEach(u->{
            CompletableFuture<User> f = CompletableFuture.supplyAsync(//异步执行方法
                    //执行耗时较长的业务代码,这里模拟一下
                    ()->{
                        //执行完成,设置返回结果 设置 coede 和 list
                        u.setAge(random.nextInt(100));
                        u.setName(UUID.randomUUID().toString());
                        return u;
                    },
                    executor
            );
            fList.add(f);
        });


        // 阻塞,等待所有任务执行完成
        CompletableFuture<Void> all= CompletableFuture.allOf(fList.toArray(new CompletableFuture[0]));

        //因为allOf没有返回值,所以需要通过thenApply回调函数获取结果
        CompletableFuture<List<User>> allUser=all.thenApply(v-> fList.stream().map(a-> {
            try {
                return a.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList()));
//        ---------------获取返回值-----------------

        try {
            list=allUser.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值