如何在Java8中使用CompletableFuture将此代码转换为异步?我用的是弹簧靴
以下是需要设置为异步的代码段:如何在Java8中使用CompletableFuture将此代码转换为异步?我用的是弹簧靴,java,multithreading,spring-boot,asynchronous,completable-future,Java,Multithreading,Spring Boot,Asynchronous,Completable Future,以下是需要设置为异步的代码段: List<Course> courses = Lists.newArrayList(); Map<String, Map<String, Student>> result = Maps.newHashMap(); for (Map<String, Object> map : jsonObject) { courses.add(getCourse(map, fee)); result.put(map.
List<Course> courses = Lists.newArrayList();
Map<String, Map<String, Student>> result = Maps.newHashMap();
for (Map<String, Object> map : jsonObject) {
courses.add(getCourse(map, fee));
result.put(map.get(GROUP), getInfoMap(map));
}
List courses=Lists.newArrayList();
Map result=Maps.newHashMap();
for(映射:jsonObject){
课程。添加(getCourse(地图,费用));
result.put(map.get(GROUP)、getInfoMap(map));
}
PS:for each循环中的映射
在两个方法调用中都没有变化,只有它们使用的信息
如何使上述代码异步运行?有两种方法被称为getCourse(map,fee)
和getInfoMap(map)
,按顺序运行它们需要相当长的时间。//启动并行操作
// start parallel operations
List<Future<Course>> coursesFut = Lists.newArrayList();
Map<String, Future<Map<String, Student>>> resultsFut = Maps.newHashMap();
for (Map<String, Object> map : jsonObjec t){
coursesFut.add(CompletableFuture.supplyAsync(() -> getCourse(map, fee)));
resultsFut.put(map.get(GROUP), CompletableFuture.supplyAsync(() -> getInfoMap(map)));
}
// collect results
List<Course> courses = Lists.newArrayList();
Map<String, Map<String, Student>> result = Maps.newHashMap();
for (Future<Course> cf : coursesFut) {
courses.add(cf.get());
}
for (Map.Entry<String, Future<Map<String, Student>> entry : resultsFut.entrySet()) {
result.put(entry.getKey(), entry.getValue().get());
}
List coursesFut=Lists.newArrayList();
Map resultsFut=Maps.newHashMap();
用于(地图:jsonObjec t){
coursefut.add(CompletableFuture.supplyAsync(()->getCourse(map,fee));
结果fut.put(map.get(GROUP),CompletableFuture.supplyAsync(()->getInfoMap(map));
}
//收集结果
List courses=Lists.newArrayList();
Map result=Maps.newHashMap();
未来课程(cf:coursesFut){
courses.add(参见get());
}
for(Map.Entry//启动并行操作
List coursesFut=Lists.newArrayList();
Map resultsFut=Maps.newHashMap();
用于(地图:jsonObjec t){
coursefut.add(CompletableFuture.supplyAsync(()->getCourse(map,fee));
结果fut.put(map.get(GROUP),CompletableFuture.supplyAsync(()->getInfoMap(map));
}
//收集结果
List courses=Lists.newArrayList();
Map result=Maps.newHashMap();
未来课程(cf:coursesFut){
courses.add(参见get());
}
对于(Map.EntryNo)来说,他们没有对地图进行变异,他们只是使用Map@MichaelOh中存储的信息,我明白了,我没有注意到Map
和infoMap
之间的区别……编辑了这个问题以避免混淆@MichaelWell你想与getInfoMap()并行运行getCourse()
,并行运行循环的多次迭代,或者两者都运行?还有,课程
列表中的顺序是否重要?不,它们不会改变地图,它们只是使用存储在map@MichaelOh中的信息,我知道,我没有注意到map
和infoMap
之间的区别……编辑了这个问题以避免混淆@MichaEL您想与getInfoMap()
并行运行getCourse()
,并行运行循环的多次迭代,还是两者都运行?另外,课程列表中的顺序是否重要?