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

查看 52|回复 1
作者: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 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("主流程完了");
    }

result, Step, tln, 执行

Plutooo   
executor1 没有 shutdown
您需要登录后才可以回帖 登录 | 立即注册

返回顶部