ori2003
V2EX  ›  Java

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

  •  
  •   ori2003 · Oct 16, 2023 · 3937 views
    This topic created in 1119 days ago, the information mentioned may be changed or developed.

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

    创建出来的是非守护线程,所以程序没有退出?
    Edward4074
    Edward4074
    Oct 16, 2023
    4
    最后加个 executor1.shutdown();
    wdf1286
    wdf1286
    Oct 17, 2023❤️1
    5
    主线程没阻塞,jvm 不退出是因为还有非 daemon 线程活着
    ori2003
    ori2003
    OP
    Oct 17, 2023
    6
    @wdf1286 是的,感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4040 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 07:41 · PVG 15:41 · LAX 23:41 · JFK 02:41
    ♥ Do have faith in what you're doing.