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);
        }
相关推荐
秋名RG3 小时前
Java 基础语法
java·开发语言
java1234_小锋4 小时前
MyBatis-Plus 3.5.15 已全面支持 Spring Boot 4.0 及 Jackson 3.0
java·spring boot·mybatis
2501_937860944 小时前
Java 文件操作与IO(下):字节流、字符流实战IO读写
java·开发语言·python
xixingzhe24 小时前
spring boot项目接口访问慢问题解决方案
java·数据库·spring boot
MetaLite4 小时前
SpringBoot整合FastJson2数据脱敏-接口日志与失败降级
java·spring boot·后端
驭渊的小故事4 小时前
java抽奖项目-奖品上传中传递参数类型的错误
java·开发语言
段一凡-华北理工大学4 小时前
高炉智能布料技术与炉料分布优化~系列文章03:布料矩阵解码:环位、角度、圈数与料流的量化控制
java·网络·人工智能·矩阵·高炉智能化·高炉布料矩阵优化·高炉智能布料技术
qfljg7 小时前
OpenRewrite 实战指南
java
Sylvia33.7 小时前
LOL实时数据接入深度解析:从WebSocket到完整数据模型
java·网络·python·websocket·网络协议
2601_9620715712 小时前
【Java报错已解决】org.springframework.beans.factory.BeanCreationException
java·开发语言