我需要创建一个泛型的 CompletableFuture
对象数组,这样我才能将其传递给 CompletableFuture.allOf
方法来获取一个 CompletableFuture
以同步线程。但是由于它是一个泛型,我无法创建它。一个显而易见的解决方案是创建一个列表,然后在其上调用 toArray
,但这将不够高效。是否有更好的方法?下面是我的代码:
// Current solution:
List<CompletableFuture<List<ReportComparable>>> newReports = new ArrayList<>();
// Loop and add CompletableFuture objects to this list
// Collect all the retrieved objects here(Sync Threads).
try {
List<List<ReportComparable>> newReps = CompletableFuture.allOf((CompletableFuture<?>[]) newReports.toArray()).get();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
allOf
不会影响各个future的完成方式。这已在创建它们时设置好了。无论哪种情况,您都在等待所有future完成,因此需要完全相同的时间。 - Holger