java – 通过Streams并行执行多个查询

前端之家收集整理的这篇文章主要介绍了java – 通过Streams并行执行多个查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下方法
  1. public String getResult() {
  2.  
  3. List<String> serversList = getServerListFromDB();
  4.  
  5. List<String> appList = getAppListFromDB();
  6.  
  7. List<String> userList = getUserFromDB();
  8.  
  9. return getResult(serversList,appList,userList);
  10. }

在这里,我按顺序调用三个方法,然后点击DB并获取结果,然后我对从DB命中获得的结果进行后处理.我知道如何通过使用Threads同时调用这三种方法.但我想使用Java 8 Parallel Stream来实现这一目标.有人可以指导我如何通过Parallel Streams实现同样的目标吗?

编辑我只想通过Stream并行调用方法.

  1. private void getInformation() {
  2. method1();
  3. method2();
  4. method3();
  5. method4();
  6. method5();
  7. }

解决方法

您可以通过以下方式使用CompletableFuture
  1. public String getResult() {
  2.  
  3. // Create Stream of tasks:
  4. Stream<Supplier<List<String>>> tasks = Stream.of(
  5. () -> getServerListFromDB(),() -> getAppListFromDB(),() -> getUserFromDB());
  6.  
  7. List<List<String>> lists = tasks
  8. // Supply all the tasks for execution and collect CompletableFutures
  9. .map(CompletableFuture::supplyAsync).collect(Collectors.toList())
  10. // Join all the CompletableFutures to gather the results
  11. .stream()
  12. .map(CompletableFuture::join).collect(Collectors.toList());
  13.  
  14. // Use the results. They are guaranteed to be ordered in the same way as the tasks
  15. return getResult(lists.get(0),lists.get(1),lists.get(2));
  16. }

猜你在找的Java相关文章