我有以下方法:
- public String getResult() {
- List<String> serversList = getServerListFromDB();
- List<String> appList = getAppListFromDB();
- List<String> userList = getUserFromDB();
- return getResult(serversList,appList,userList);
- }
在这里,我按顺序调用三个方法,然后点击DB并获取结果,然后我对从DB命中获得的结果进行后处理.我知道如何通过使用Threads同时调用这三种方法.但我想使用Java 8 Parallel Stream来实现这一目标.有人可以指导我如何通过Parallel Streams实现同样的目标吗?
- private void getInformation() {
- method1();
- method2();
- method3();
- method4();
- method5();
- }
解决方法
您可以通过以下方式使用CompletableFuture:
- public String getResult() {
- // Create Stream of tasks:
- Stream<Supplier<List<String>>> tasks = Stream.of(
- () -> getServerListFromDB(),() -> getAppListFromDB(),() -> getUserFromDB());
- List<List<String>> lists = tasks
- // Supply all the tasks for execution and collect CompletableFutures
- .map(CompletableFuture::supplyAsync).collect(Collectors.toList())
- // Join all the CompletableFutures to gather the results
- .stream()
- .map(CompletableFuture::join).collect(Collectors.toList());
- // Use the results. They are guaranteed to be ordered in the same way as the tasks
- return getResult(lists.get(0),lists.get(1),lists.get(2));
- }