CompletableFuture with supplyAsync 未按预期工作

CompletableFuture with supplyAsync not working as expected

我正在用 Java CompletableFuture 做一些实验。这是代码

public class SpringBootAsyncApplication {

    public static void main(String[] args) {

        CompletableFuture.supplyAsync(() - > {

            return MailUtil.getMailInfo();

        }).thenAccept(content - > {
            System.out.println("Mail content: " + content);
        });
    }

}

class MailUtil {
    public static String getMailInfo() {
        return "Your email content";
    }

    public static boolean sendMail() {
        System.out.println("Send mail: completed");
        return true;
    }

    public static void logging() {
        System.out.println("Log: Send mail at " + System.currentTimeMillis());
    }
}

我运行这个程序3遍了。他们都没有 return 任何输出?但是当我用数字 5

替换 return MailUtil.getMailInfo();
CompletableFuture.supplyAsync(() - > {

    return 5;

}).thenAccept(content - > {
    System.out.println("Mail content: " + content);
});

然后它 运行 就正常了。这是为什么?

您看到的结果纯属巧合。主线程在您的异步任务 executed/completed 之前退出。在末尾添加 CompletableFuture::join,您将始终看到结果:

CompletableFuture.supplyAsync(() - > {

    return MailUtil.getMailInfo();

}).thenAccept(content - > {
    System.out.println("Mail content: " + content);
}).join();

这是因为当您使用 supplyAsync 时,您的任务将在来自 ForkJoinPool.commonPool 的线程之一中执行,并且默认情况下来自该池的线程是守护线程,因此它们不会阻止 JVM 退出.您可以通过检查与 commonPool 关联的默认线程工厂来验证这一点:

ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
ForkJoinWorkerThread forkJoinWorkerThread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(forkJoinPool);

boolean daemon = forkJoinWorkerThread.isDaemon();
System.out.println(daemon);

输出为true