—— 阿尔伯特·爱因斯坦

程序员の奇妙冒险

Spring BootJavaSpringSpring Boot
2025-07-24 16:35阅读:28评论:0

java 异步查询统计提高效率

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
List<String> idList = Lists.newArrayList("111");
List<CompletableFuture<Integer>> batchFutures = new ArrayList<>();
for (String id : idList) {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
Integer num = 0;//这里模拟查询统计操作
return num;
});
batchFutures.add(future);
}
 
CompletableFuture<List<Integer>> all = CompletableFuture.allOf(batchFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> batchFutures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
List<Integer> integers = null;
try {
integers = all.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
 
int num = 0;
for (Integer integer : integers) {
if (integer != null) {
num += integer;
}
}
 
评论(0)
暂无评论来抢沙发吧~