V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ori2003
V2EX  ›  Java

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

  •  
  •   ori2003 · 194 天前 · 1147 次点击
    这是一个创建于 194 天前的主题,其中的信息可能已经有所发展或是发生改变。

    正常 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("主流程完了");
    
        }
    
    6 条回复    2023-10-17 09:40:12 +08:00
    Plutooo
        1
    Plutooo  
       194 天前   ❤️ 6
    executor1 没有 shutdown
    admin7785
        2
    admin7785  
       194 天前 via iPhone
    美团技术平台文章里的代码?他那个不完整
    https://mp.weixin.qq.com/s/GQGidprakfticYnbVYVYGQ
    seedscoder
        3
    seedscoder  
       194 天前
    ```
    ExecutorService executor1 = Executors.newFixedThreadPool(5);
    ```

    创建出来的是非守护线程,所以程序没有退出?
    Edward4074
        4
    Edward4074  
       194 天前
    最后加个 executor1.shutdown();
    wdf1286
        5
    wdf1286  
       193 天前   ❤️ 1
    主线程没阻塞,jvm 不退出是因为还有非 daemon 线程活着
    ori2003
        6
    ori2003  
    OP
       193 天前
    @wdf1286 是的,感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2796 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:16 · PVG 20:16 · LAX 05:16 · JFK 08:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.