JAVA 分割集合 多线程 分批次操作
分割集合工具类(我还写了一个更全面的的工具类可以了解一下)
https://blog.youkuaiyun.com/Mclaughling/article/details/113247668
/**
* 讲一个List的集合分割成多个用于批量处理
* @param source 总量集合
* @param n 分成几份
* @param <T> 泛型
* @return 分割后的子集合
*/
public static <T> List<List<T>> averageAssignList(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remainder = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List<T> value = null;
if (remainder > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remainder--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}
service 调用方法
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
List<NameZ> list = createList();
int i = 20;
List<List<NameZ>> lists = averageAssign(list, i);
System.out.println("主线程开始");
//创建线程池子
ExecutorService executorService = Executors.newCachedThreadPool();
//线程同步围栏
CountDownLatch cdl = new CountDownLatch(i);
long end = System.currentTimeMillis();
System.out.println((end - start)/1000 + "秒");
long startList = System.currentTimeMillis();
//线程池中取线程 执行集合
lists.forEach((a)->
executorService.submit(() -> {
dealWith(a);
cdl.countDown();
}
));
//主线程等待子线程执行完成再继续执行
cdl.await();
//关闭线程池
executorService.shutdown();
System.out.println("主线程结束");
long endList = System.currentTimeMillis();
System.out.println((endList - startList) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
测试
创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NameZ {
private Integer id;
private String name;
private String app;
}
创建集合
public static List<NameZ> createList() {
List<NameZ> strings = new ArrayList<>();
for (int i=0;i<=10000000;i++){
String s = UUID.randomUUID().toString().replaceAll("-", "").replaceAll(" ", "");
strings.add(new NameZ(i, s,"app"));
}
return strings;
}
模拟方法处理数据
private static void dealWith(List<NameZ> list){
for (NameZ nameZ : list) {
nameZ.setApp("bpp");
}
System.out.println(JSON.toJSONString(list.get(0)));
}
总结
可以使用此思路 完成数据批量存储 以及大集合的处理