Java CompletableFuture 使用问题?大佬帮忙看看

2023 年 10 月 16 日
 ori2003

正常 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("主流程完了");

    }
3937 次点击
所在节点    Java
6 条回复
Plutooo
2023 年 10 月 16 日
executor1 没有 shutdown
admin7785
2023 年 10 月 16 日
美团技术平台文章里的代码?他那个不完整
https://mp.weixin.qq.com/s/GQGidprakfticYnbVYVYGQ
seedscoder
2023 年 10 月 16 日
```
ExecutorService executor1 = Executors.newFixedThreadPool(5);
```

创建出来的是非守护线程,所以程序没有退出?
Edward4074
2023 年 10 月 16 日
最后加个 executor1.shutdown();
wdf1286
2023 年 10 月 17 日
主线程没阻塞,jvm 不退出是因为还有非 daemon 线程活着
ori2003
2023 年 10 月 17 日
@wdf1286 是的,感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/982520

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX