为什么不执行 CompletableFuture.runAsync?

0 java java.util.concurrent

我认为主线程必须在子线程之后结束。但是下面的代码显示在打印“异步结束”之前完成的过程。是什么原因?谁能解释一下?谢谢。

import java.util.concurrent.CompletableFuture;

public class Test {
    public static void main(String[] args) {
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("async start");
                Thread.sleep(3000);
                System.out.println("async end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("main end");
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 5

它被执行了,你只是不等待结果。

的 JavadocCompleteableFuture.runAsync()说:

返回一个新的 CompletableFuture,ForkJoinPool.commonPool() 它在运行给定操作后由运行在 中的任务异步完成 。

的 JavadocForkJoinPool.commonPool()说:

任何依赖异步任务处理在程序终止之前完成的程序都应该commonPool().awaitQuiescence()在退出之前调用 , 。

所以,调用它。