2017-03-02 16 views
1

我在java中有一個List<List<String>>,我想在父列表內異步處理List,並使用固定線程池示例3.我正嘗試在java 8中使用CompletableFuture和Stream。我不理解如何合併這兩個以及如何繼續。 PFB代碼我已經嘗試過。在處理器中,我只是打印它,但我會做數據庫操作。如何在java中使用CompletableFuture處理List列表?

所以在這裏我想要流List<List<String>>並創建基於列表大小的線程數量,但鋤頭將流列表作爲參數傳遞給Processor with CompletableFuture。

public class CompletableFutureWithList { 
    public static void main(String args[]) { 
     List<List<String>> aList = new ArrayList<>(); 
     aList.add(new ArrayList<>(Arrays.asList("xyz", "abc"))); 
     aList.add(new ArrayList<>(Arrays.asList("qwe", "poi"))); 
     System.out.println("helo..."); 
     ExecutorService executor = Executors.newFixedThreadPool(aList.size()); 
     //aList.stream().flatMap(List::stream). 
     Processor aProcessor = new Processor(); 
     List<String> tempList = new ArrayList<>(); 
     CompletableFuture aComFuture = supplyAsync(() -> aProcessor.processList(tempList), executor); 
     try { 
      aComFuture.get(); 
     } catch (InterruptedException | ExecutionException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
public class Processor { 
    public boolean processList(List<String> tempList) { 
     for (String string : tempList) { 
      System.out.println("Output: " + string); 
     } 
     return true; 
    } 
} 
+2

'未來 F = excecutor.submit(() - > PROCESSLIST(列表))'每個列表? – assylias

+0

你可以編寫簡單的程序,它有一個線程(簡單調試),並運行該程序使用執行外部進程Apache Commons Exec。 – Grzesiek

回答

1

所以,從我的理解,你需要打電話給你的處理器爲每個List<String>裏面你List<List<String>>

所以你可以做的是創造一切的使用CompletableFuture新線程然後等待他們全部完成並對返回的值進行任何處理。

所以你可以做的是這樣的事情

List<List<String>> aList = new ArrayList<>(); 

//Create all CFs 
List<CompletableFuture<Boolean>> futureList = aList.stream() 
      .map(strings -> CompletableFuture.supplyAsync(() -> processList(strings), executor)) 
      .collect(toList()); 

//Wait for them all to complete 
CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join(); 

//Do processing of the results 
Stream<Boolean> booleanStream = futureList.stream() 
      .map(CompletableFuture::join); 
//Do other stuff you need 
0

這是如何合併列表和completablefuture名單。

你爲什麼要使用CompletableFuture,而不是簡單地調用
public static void main(String args[]) { 
    List<List<String>> aList = new ArrayList<>(); 
    aList.add(new ArrayList<>(Arrays.asList("xyz", "abc"))); 
    aList.add(new ArrayList<>(Arrays.asList("qwe", "poi"))); 
    System.out.println("hello..."); 

    Processor aProcessor = new Processor(); 
    List<String> tempList = new ArrayList<>(); 
    CompletableFuture aComFuture = CompletableFuture.supplyAsync(() -> ""); 

    aList.stream() 
      .forEach(list -> aComFuture.thenApply(fn -> aProcessor.processList(list))); 

    aComFuture.join(); 
} 

static class Processor { 
    public boolean processList(List<String> tempList) { 
     for (String string : tempList) { 
      System.out.println("Output: " + string); 
     } 
     return true; 
    } 
} 
相關問題