2017-10-05 25 views
-3

我正試圖實現這樣的事情。這是一個表達意圖的例子。如何在循環中調用可完成的未來併合並所有結果?

我希望所有完整的期貨能夠執行並將所有結果合併到一個結果並返回。因此,對於下面的示例,集合allResults應該包含字符串「one」,「two」,「three」,每個3次。我希望他們都能並行運行而不是連續運行。

任何指向我可以用來實現這一目標的可補充未來的API的指針都是非常有用的。

public class Main { 


    public static void main(String[] args) { 

     int x = 3; 
     List<String> allResuts; 

     for (int i = 0; i < x; i++) { 

      //call getCompletableFutureResult() and combine all the results 
     } 

    } 

    public static CompletableFuture<List<String>> getCompletableFutureResult() { 

     return CompletableFuture.supplyAsync(() -> getResult()); 
    } 

    private static List<String> getResult() { 


     List<String> list = new ArrayList<>(); 
     list.add("one"); 
     list.add("two"); 
     list.add("three"); 

     return list; 
    } 


} 
+0

定義_combine_。 –

回答

1

不能收集結果在第一for循環,因爲這將意味着你甚至沒有啓動其他任務,同時等待前面的任務的結果。

因此,一旦所有任務開始,就開始收集結果。

public static void main(String[] args) throws Exception 
{ 
    int x = 3; 

    Queue<CompletableFuture<List<String>>> cfs = new ArrayDeque<>(x); 
    for (int i = 0; i < x; i++) 
    { 
    cfs.add(getCompletableFutureResult()); 
    } 

    List<String> allResuts = new ArrayList<>(); 
    for (CompletableFuture<List<String>> cf : cfs) 
    allResuts.addAll(cf.get()); 

    System.out.println(allResuts); 
} 
1

有來自文卡塔拉朱答案的問題。 Raju使用得到調用將來這是一個阻塞調用,並殺死了Async風格編碼的主要目的。總是避免做期貨。

有大量內置的方法建立一個圍繞處理像thenApply,thenAccept,thenCompose,thenCombine等

CompletableFuture.allOf方法是指當你不得不處理多個期貨使用未來值。

它具有這樣的簽名如下

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) 

旁註:CompletableFuture.anyOf可以當你只關心未來第一完成使用。當您需要完成所有期貨時,請使用allOf

我會使用CompletableFuture.allOf按以下方式編碼您的規範。

public class DorjeeTest { 


    public static CompletableFuture<List<String>> getCompetableFutureResult() { 
     return CompletableFuture.supplyAsync(() -> getResult()); 
    } 
    public static List<String> getResult() { 
     return Lists.newArrayList("one", "two", "three"); 
    } 

    public static void testFutures() { 
     int x = 3; 
     List<CompletableFuture<List<String>>> futureResultList = Lists.newArrayList(); 
     for (int i = 0; i < x; i++) { 
      futureResultList.add(getCompetableFutureResult()); 
     } 

     CompletableFuture[] futureResultArray = futureResultList.toArray(new CompletableFuture[futureResultList.size()]); 

     CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futureResultArray); 

     CompletableFuture<List<List<String>>> finalResults = combinedFuture 
       .thenApply(voidd -> 
         futureResultList.stream() 
           .map(future -> future.join()) 
         .collect(Collectors.toList())); 

     finalResults.thenAccept(result -> System.out.println(result)); 
    } 


    public static void main(String[] args) { 
     testFutures(); 
     System.out.println("put debug break point on this line..."); 

    } 
} 
相關問題