关于CompletableFuture的疑惑

当我使用CompletableFuture的默认线程池时,只输出:main线程结束了,为什么不输出:最终结果为=

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("最终结果为=" + v);
            }
        }).exceptionally(e -> {
            System.out.println("出现异常=" + e);
            return null;
        });
        System.out.println("main线程结束了");
    }
}

以下内容部分参考ChatGPT模型:


这是因为主线程在启动CompletableFuture后就立刻结束了,而CompletableFuture是在另一个线程中执行的,所以主线程并不会等到CompletableFuture执行完毕再退出。如果想要让主线程等待CompletableFuture执行完毕后再退出,可以使用CompletableFuture的join方法。

例如:

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("最终结果为=" + v);
            }
        }).exceptionally(e -> {
            System.out.println("出现异常=" + e);
            return null;
        });

        System.out.println("main线程结束了");

        future.join(); // 等待CompletableFuture执行完毕
    }
}

如果我的建议对您有帮助、请点击采纳、祝您生活愉快