并行查询

2024-03-12  本文已影响0人  逆风踏雷
//并行查询的写法
final CountDownLatch latch = new CountDownLatch(5);
ExecutorService threadPool = Executors.newFixedThreadPool(5);
List<Future<String>> futureTaskList = new ArrayList<Future<String>>(5);
for (int i = 0; i < 5; i++) {
futureTaskList.add(threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
latch.countDown();
return "ok...";
}
}));
}
try {
latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}

try {
for (Future<String> future : futureTaskList) {
System.out.println(future.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

//stream 写法  参考:https://www.jb51.cc/java/128062.html
1.  public  String getResult()  {

3.  // Create Stream of tasks:
4.  Stream<Supplier<List<String>>> tasks =  Stream.of(
5.  ()  -> getServerListFromDB(),()  -> getAppListFromDB(),()  -> getUserFromDB());

7.  List<List<String>> lists = tasks
8.  // Supply all the tasks for execution and collect [CompletableFuture](https://www.jb51.cc/tag/CompletableFuture/)s
9.  .map([CompletableFuture](https://www.jb51.cc/tag/CompletableFuture/)::supplyAsync).collect(Collectors.toList())
10.  // Join all the [CompletableFuture](https://www.jb51.cc/tag/CompletableFuture/)s to gather the results
11.  .stream()
12.  .map([CompletableFuture](https://www.jb51.cc/tag/CompletableFuture/)::join).collect(Collectors.toList());

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.  }

//TODO fork/join 写法
//TODO CompletableFuture 写法  https://www.deathearth.com/1503.html
//TODO 结合spring 的写法  https://juejin.cn/post/6844904040359280648
//https://github.com/lvyahui8/spring-boot-data-aggregator

//TODO: 很好的使用了CountDownLaunch的写法 可以及时终止
https://blog.csdn.net/qq_35264464/article/details/79604414
上一篇下一篇

猜你喜欢

热点阅读