java – 通过Streams并行执行多个查询
发布时间:2020-12-15 02:52:25 所属栏目:Java 来源:网络整理
导读:我有以下方法: public String getResult() { ListString serversList = getServerListFromDB(); ListString appList = getAppListFromDB(); ListString userList = getUserFromDB(); return getResult(serversList,appList,userList); } 在这里,我按顺序调
我有以下方法:
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实现同样的目标吗? 编辑我只想通过Stream并行调用方法. 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)); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |