正常 main 方法执行完之后会退出:Process finished with exit code 0
但是我执行下边的代码,主线程阻塞了,为什么不退出呢? 执行结果如下:
执行 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<String> cf1 = CompletableFuture.supplyAsync(() -> {
System.out.println("执行 step 1");
return "step1 result";
}, executor1);
CompletableFuture<String> 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("主流程完了");
}
1
Plutooo 2023-10-16 17:57:07 +08:00 6
executor1 没有 shutdown
|
2
admin7785 2023-10-16 18:22:42 +08:00 via iPhone
美团技术平台文章里的代码?他那个不完整
https://mp.weixin.qq.com/s/GQGidprakfticYnbVYVYGQ |
3
seedscoder 2023-10-16 18:29:30 +08:00
```
ExecutorService executor1 = Executors.newFixedThreadPool(5); ``` 创建出来的是非守护线程,所以程序没有退出? |
4
Edward4074 2023-10-16 19:50:46 +08:00
最后加个 executor1.shutdown();
|
5
wdf1286 2023-10-17 08:16:24 +08:00 1
主线程没阻塞,jvm 不退出是因为还有非 daemon 线程活着
|