但是我执行下边的代码,主线程阻塞了,为什么不退出呢?
执行结果如下:
执行 step 1
主流程 0.5 完了
主流程完了
执行 step 2
step1 result , step2 result
执行 step 3
step3 result
代码在这里:
public static void main(String[] args) {
ExecutorService executor1 = Executors.newFixedThreadPool(5);
CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> {
System.out.println("执行 step 1");
return "step1 result";
}, executor1);
CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("执行 step 2");
return "step2 result";
}, executor1);
System.out.println("主流程 0.5 完了");
cf1.thenCombine(cf2, (result1, result2) -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(result1 + " , " + result2);
System.out.println("执行 step 3");
return "step3 result";
}).thenAccept(result3 -> System.out.println(result3));
System.out.println("主流程完了");
}