Why CompletableFuture.runAsync is not executed?

点点圈 提交于 2020-12-27 05:41:19

问题


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

回答1:


It is executed, you just aren't waiting for the result.

The Javadoc of CompleteableFuture.runAsync() says:

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() after it runs the given action.

The Javadoc of ForkJoinPool.commonPool() says:

Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence(), before exit.

So, invoke that.



来源:https://stackoverflow.com/questions/56054176/why-completablefuture-runasync-is-not-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!