当您可以使用直接的CompletableFuture.supplyAsync
链接相同的依赖函数时,不要在传递给thenCompose
的函数中执行thenApplyAsync
。
通过thenApplyAsync
绑定从属函数可以让您在完成第一步之前获取代表这些步骤的CompletableFuture
实例,因此您可以将它们全部收集到List
中以等待它们的完成。结束时完成,不需要通过CompletableFuture.allOf
创建复合期货。
public void test() {
// Gather CompletableFutures to wait for them at the end
List<CompletableFuture<?>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int finalI = i;
CompletableFuture<String> step1 = CompletableFuture.supplyAsync(() -> {
logger.debug("Start step 1 - " + finalI);
simulateLongProcessing();// just waits for 1 s
logger.debug("End step 1 - " + finalI);
return "step1 output - " + finalI;
});
// Second step : Chain several sub-tasks based on the result of the first step
for (int j = 0; j < 50; j++) {
final int finalJ = j;
futures.add(step1.thenApplyAsync(s -> {
logger.debug("Start - step 2 : " + s + " | " + finalJ);
simulateLongProcessing();
logger.debug("End - step 2 : " + s + " | " + finalJ);
return "step2 output - " + s + " | " + finalJ;
}));
}
}
// Wait for the completion
for (CompletableFuture<?> future : futures) {
future.join();
}
}
本文链接:https://www.f2er.com/3100625.html