我遇到了需要用CompletableFuture
實現遞歸的情況。無論何時CompletableFuture
s返回任何結果,我都想致電recursionFuture(ex)
,但我不確定該如何實現該結果。在當前情況下,只有當future1
和future2
返回輸出,然後檢查條件時才調用recursionFuture(ex)
。任何幫助,將不勝感激。如何在不等待輸出的情況下繼續CompletableFuture
public static void recursionFuture(ExecutorService ex)
{
try
{
CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);
CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> new ConcurrencyPoC_CompletableFuture().executeTask(), ex);
if (future1.get() != null | future2.get() != null)
{
System.out.println("Future1: " + future1.get() + " Future2: " + future2.get());
recursionFuture(ex);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
謝謝安德魯,這個工程,但有一個小問題。由於遞歸,即使executeTask()沒有返回任何東西並繼續無限期地繼續執行代碼。是否有可能檢查未來的輸出像futire1.get()!= null然後調用遞歸,但與前面提到的問題發生。你能在這裏建議嗎? –
嗯,我通過編輯代碼一樣得到這個工作:CompletableFuture.anyOf(future1,future2).thenRunAsync(() - > \t \t \t { \t \t \t \t recursionFuture(除息); \t \t \t} \t \t ex); \t \t \t,ex); –