2017-05-03 91 views
-2

我是新來CompletableFuture, 這裏是一個簡單的,我想嘗試以下使用CompletableFuture時出現了什麼問題?

CompletableFuture.supplyAsync(()-> {System.out.println("async");}); 

當我嘗試編譯,它給了錯誤

Error:(23, 26) java: no suitable method found for supplyAsync(()->{ Syst[...]"); }) 
    method java.util.concurrent.CompletableFuture.<U>supplyAsync(java.util.function.Supplier<U>) is not applicable 
     (cannot infer type-variable(s) U 
     (argument mismatch; bad return type in lambda expression 
      missing return value)) 
    method java.util.concurrent.CompletableFuture.<U>supplyAsync(java.util.function.Supplier<U>,java.util.concurrent.Executor) is not applicable 
     (cannot infer type-variable(s) U 
     (actual and formal argument lists differ in length)) 

我想知道什麼是錯的以上?

+3

那麼你不返回任何東西 - 什麼樣的「供應商」你以爲你傳遞? –

+1

您缺少返回https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#supplyAsync-java.util.function.Supplier- –

+4

您應該使用'CompletableFuture .runAsync(() - > System.out.println(「async」));'而是。 – Flown

回答

2

就像在錯誤消息稱:

缺少返回值

供應商必須返回一個值。嘗試:

CompletableFuture.supplyAsync(()-> {System.out.println("async"); return null;}); 

,或者像飛揚指出,使用runAsync

CompletableFuture.runAsync(()-> System.out.println("async")); 
+0

它的工作原理,但有沒有一種方法不使用「返回null」 –

+2

當然:返回任何你喜歡的東西。但要重複一遍:「供應商不得不退貨」。如果它沒有返回,它是一個'Runnable',而不是'Supplier'。 –

+0

@Adam Lee:如果你堅持使用'supplyAsync'儘管沒有提供任何東西,你可以使用'CompletableFuture.supplyAsync(() - > System.out.append(「async \ n」))'' – Holger