Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:CompletableFuture.SupplySync()不调用异步方法_Java_Future_Completable Future - Fatal编程技术网

Java:CompletableFuture.SupplySync()不调用异步方法

Java:CompletableFuture.SupplySync()不调用异步方法,java,future,completable-future,Java,Future,Completable Future,让我们假设以下主要方法: public class Async { public static void main(String[] args) throws Exception { CompletableFuture.supplyAsync(Async::sendMsg); System.out.println(Thread.currentThread().getName()); } public static String se

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

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

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

这是因为使用了中,一旦程序(主线程)终止,任务将自动终止。

有简单的解决方法吗?捕获调用
CompletableFuture.supplySync
返回的
CompletableFuture
。然后,在
System.out.print….
语句之后,调用
future.get()
。然后,主线程将等待后台线程也完成运行。但是future.get()会阻止主线程…@user3133542这是正确的。对于您发布的简单代码,它将起作用,您将看到两个线程都打印它们的名称。如果您有其他想法,请分享,以便我们可以帮助您。