Java:CompletableFuture.SupplyAsync()不调用异步方法 [英] Java: CompletableFuture.supplyAsync() do no invoke asynchronous method

查看:30
本文介绍了Java:CompletableFuture.SupplyAsync()不调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设以下主要方法:

public class Async {
    public static void main(String[] args) throws Exception {

        CompletableFuture.supplyAsync(Async::sendMsg);
        System.out.println(Thread.currentThread().getName());


    }

    public static String sendMsg() {
        try {
            TimeUnit.SECONDS.sleep(5);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

我只想进行一个异步调用,而不阻塞Main-Thread。但控制台仅输出以下字符串:

main

sendMsg-方法的输出似乎未被调用。但是为什么呢?我错过了什么吗?

推荐答案

是因为CompletableFuture.supplyAsync(Supplier)使用common ForkJoinPool,一旦程序(主线程)终止,任务将自动终止。

这篇关于Java:CompletableFuture.SupplyAsync()不调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆