本文介紹了Java:CompletableFuture.SupplyAsync()不調(diào)用異步方法的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
讓我們假設(shè)以下主要方法:
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;
}
}
我只想進(jìn)行一個(gè)異步調(diào)用,而不阻塞Main-Thread。但控制臺(tái)僅輸出以下字符串:
main
sendMsg
-方法的輸出似乎未被調(diào)用。但是為什么呢?我錯(cuò)過了什么嗎?
推薦答案
是因?yàn)镃ompletableFuture.supplyAsync(Supplier)使用common ForkJoinPool,一旦程序(主線程)終止,任務(wù)將自動(dòng)終止。
這篇關(guān)于Java:CompletableFuture.SupplyAsync()不調(diào)用異步方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,