已解决
CompletableFuture 异步调用,获取返回值
来自网友在路上 187887提问 提问时间:2023-11-03 16:45:14阅读次数: 87
最佳答案 问答题库878位专家为你答疑解惑
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 和 listu.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);}
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"CompletableFuture 异步调用,获取返回值":http://eshow365.cn/6-31223-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!