private String print(int index) {
try {
Thread.sleep((5+index) * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
String str = "Completed!!" + index;
log.info(str);
return str;
}
@Test
public void allOfTest() throws Exception {
log.info("allOfTest START");
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> print(0)); //sleep 5
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> print(1)); //sleep 6
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> print(2)); //sleep 7
// callback 에서 머지하지 않는 경우
CompletableFuture.allOf(cf1, cf2, cf3).thenAcceptAsync(s -> log.info("result 1: {}", s));
// wait until they are all done
List<CompletableFuture<String>> completableFutures = Arrays.asList(cf1, cf2, cf3);
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[3]))
.thenApplyAsync(
result -> completableFutures.stream().map(future -> future.join()).collect(Collectors.toList()))
.thenAcceptAsync(messages -> messages.forEach(message -> log.info("result 2: {}", message))); //몇 초 뒤 찍힐까요?
log.info("allOfTest END"); // 몇 초 뒤에 찍힐까요?
Thread.sleep(11 * 1000L);
}