2017-03-02 15 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; 
    } 
} 
相关问题