简体   繁体   English

为什么不执行CompletableFuture.runAsync?

[英]Why CompletableFuture.runAsync is not executed?

I consider that main thread must end after sub thread.But below code shows the process finished before print the "async end".What is the reason?Can anybody explain?Thx. 我认为主线程必须在子线程之后结束。但是下面的代码显示了在打印“异步结束”之前完成的过程。原因是什么?有人可以解释吗?

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");
    }
}

It is executed, you just aren't waiting for the result. 它已执行,您只是在等待结果。

The Javadoc of CompleteableFuture.runAsync() says: CompleteableFuture.runAsync()的Javadoc说:

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() after it runs the given action. 返回一个新的CompletableFuture,它由运行给定操作的ForkJoinPool.commonPool()运行的任务异步完成。

The Javadoc of ForkJoinPool.commonPool() says: ForkJoinPool.commonPool()的Javadoc说:

Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence() , before exit. 任何在程序终止之前依赖异步任务处理完成的程序都应在退出之前调用commonPool().awaitQuiescence()

So, invoke that. 因此,调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM