1 需求
将一个数据量很大的集合,异步分批进行处理,然后再把每批数据进行整合
2 代码示例
public class BatchTest {
// 定义每批处理的数量
private static final int BATCH_SIZE = 3;
// 定义总数
private static final int TOTAL_SIZE = 10;
public static void main(String[] args) {
// 创建一个大小为总数据量(TOTAL_SIZE)的数据集合
List<Integer> dataList = new ArrayList<>();
for (int i = 1; i <= TOTAL_SIZE; i++) {
dataList.add(i);
}
// 总批次
int totalPageCount = (dataList.size() % BATCH_SIZE == 0) ? dataList.size() / BATCH_SIZE : dataList.size() / BATCH_SIZE + 1;
System.out.println("总批次为:" + totalPageCount + "次");
// 创建一个异步任务集合
List<CompletableFuture<List<Integer>>> futures = new ArrayList<>();
// 进行批次处理
for (int i = 0; i < totalPageCount; i++) {
// 获取每批的数据
List<Integer> partList = dataList.stream().skip(i * BATCH_SIZE).limit(BATCH_SIZE).collect(Collectors.toList());
// 开始任务
CompletableFuture<List<Integer>> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000); // 模拟接口调用时间
} catch (InterruptedException e) {
e.printStackTrace();
}
// 调用处理每批数据的接口
List<Integer> result = callApi(partList);
System.out.println(Thread.currentThread().getId() + ": " + result);
return result;
});
futures.add(future);
}
// 等待所有的异步线程都完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
// 将每批处理完的数据整合
List<Integer> collect = futures.stream()
.map(future -> {
// 获取每个异步线程执行后的结果
List<Integer> join = future.join();
System.out.println("异步执行后的结果:" + join);
return join;
})
.flatMap(a -> {
System.out.println("a = " + a);
return a.stream();
})
.collect(Collectors.toList());
System.out.println("整合之后的结果为:" + collect);
}
/**
* 模拟数据处理的方法
* @param subList
* @return
*/
private static List<Integer> callApi(List<Integer> subList) {
return subList;
}
}
控制台输出:
总批次为:4次
14: [10]
12: [4, 5, 6]
13: [7, 8, 9]
11: [1, 2, 3]
异步执行后的结果:[1, 2, 3]
a = [1, 2, 3]
异步执行后的结果:[4, 5, 6]
a = [4, 5, 6]
异步执行后的结果:[7, 8, 9]
a = [7, 8, 9]
异步执行后的结果:[10]
a = [10]
整合之后的结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]