@Test
void testFuture() throws ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->task1());
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(()->task2());
log.info("并行执行");
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1,future2);
allFutures.get();
log.info(future1.get() + "result " + future2.get());
}
String task1(){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "task1 completed";
}
String task2(){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "task2 completed";
}
执行结果:文章来源地址https://uudwc.com/A/Oqbo2
12:10:32.855 [main] INFO c.c.b.e.c.Test - [testFuture:247] - 并行执行
12:10:36.857 [main] INFO c.c.b.e.c.Test - [testFuture:250] - task1 completed result task2 completed
文章来源:https://uudwc.com/A/Oqbo2