【发布时间】:2019-12-04 19:20:45
【问题描述】:
Java 8 环境。
同时使用 CompletableFuture.allOf() 运行任务并且 然后从每个线程获取每个结果,然后将所有结果组合成一个组合结果并返回。
在下面的代码中,要获得结果 ( = List<Student> ),它不必是 I. 和 II 之间的代码。
他们说我需要使用 join() 但没有用
我还从
获得了一些 allOf()Java 8 CompletableFuture.allOf(...) with Collection or List
和其他链接,但对我没有任何作用。
我想我错过了一些非常简单的部分。有人知道如何让它工作吗?
public class Test1 {
public static void main(String[] args) {
Test1 t = new Test1();
Map<Major, List<Student>> allMajorStudentListMap = new HashMap<>();
// fill out some data toallMajorStudentListMap
t.getData(allMajorStudentListMap);
}
List<Student> getData(Map<Major, List<Student>> allMajorStudentListMap) {
List<CompletableFuture<List<Student>>> completableFutures = new ArrayList<>();
// suppose the size of completableFutures is 10
for(Map.Entry<Major, List<Student>> entry: allMajorStudentListMap.entrySet()) {
CompletableFuture<List<Student>> future = CompletableFuture.supplyAsync(() -> getDetailedStudents(entry));
completableFutures.add(future);
}
// want to run 10 jobs concurrently --> get the 10 result and then combine these 10 results into one
// finally want to sent the combined 10 results at one in this method
// I. ======================= I got this code from somewhere ==========================
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]))
.exceptionally(ex -> null)
.join();
Map<Boolean, List<CompletableFuture<List<Student>>>> result =
completableFutures.stream()
.collect(Collectors.partitioningBy(CompletableFuture::isCompletedExceptionally));
result.forEach((k, clist) -> {
System.out.printf("k = " + k);
for(CompletableFuture<List<Student>> student: clist) {
// 3) don't know how to get only List<Student> and then print here
// tried this and that but didn't work
// student.get() has compile error
}
});
// II. =============================================================================================
// want to return combined List<Student>
return ???;
}
List<Student> getDetailedStudents(Map.Entry<Major, List<Student>> entry)
{
List<Student> studentList = new ArrayList<>();
Major major = entry.getKey();
String majorCode = major.getMajorCode();
String majorName = major.getMajorName();
List<Student> studentListList = entry.getValue();
studentList.addAll(getDataFromRemote(majorCode, majorName, studentList)));
return studentList;
}
List<Student> getDataFromRemote(String majorCode, String majorName, List<studentList> studentList) {
// do something and then return list of Student
return detailedStudentList;
}
}
【问题讨论】:
标签: java java-8 concurrency