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);
        }
相关推荐
风象南7 分钟前
SpringBoot 控制器的动态注册与卸载
java·spring boot·后端
我是一只代码狗33 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好1 小时前
JDK 代理原理
java·spring boot·spring
PanZonghui1 小时前
Centos项目部署之Java安装与配置
java·linux
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh2 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华2 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
coding and coffee2 小时前
狂神说 - Mybatis 学习笔记 --下
java·后端·mybatis
千楼2 小时前
阿里巴巴Java开发手册(1.3.0)
java·代码规范
reiraoy2 小时前
缓存解决方案
java