当需要对一个集合中有一千或者一万的数据需要进行操作时,单线程会降低效率,为了提高执行效率,可以将该集合分割为多个小集合,然后利用多线程进行批量同步运行,提高效率。
1、集合拆分工具类
/**
* 拆分list集合 (后期如果使用次数多,可将其封装在工具类中)
* 可将给定old集合根据sublength大小分割为多个 集合大小为 sublength的集合
* @param oldList 需要拆分的集合
* @param subLength 拆分的大小
* @return
* @param <T>
*/
private static <T> List<List<T>> splitList(List<T> oldList, int subLength){
ArrayList<List<T>> returnList = new ArrayList<>();
ArrayList<T> newChildList = new ArrayList<>();
if (CollectionUtils.isEmpty(oldList) || subLength <=0){
returnList.add(newChildList);
return returnList;
}
int size = oldList.size();
if(subLength >= size){
//数量不足sublength指定大小
returnList.add(oldList);
return returnList;
}
int pre = size/subLength; //共可以分为多少个大小为subLength的子集合
int last = size%subLength;//剩余不够subLength的集合
// 将oldList分为:前面pre个集合,每个大小subLength
for (int i = 0; i < pre; i++) {
ArrayList<T> itemList = new ArrayList<>();
for (int j = 0; j < subLength; j++) {
itemList.add(oldList.get(i * subLength + j));
}
returnList.add(itemList);
}
// last进行处理
if (last > 0){
ArrayList<T> itemList = new ArrayList<>();
for (int i = 0; i < last; i++) {
itemList.add(oldList.get(pre * subLength + i));
}
returnList.add(itemList);
}
return returnList;
}
2、操作业务代码,使用多线程执行
/**
* 人员id保存
*/
public void handleByThread(List<String> idList) throws AppException, InterruptedException {
//将ids进行分割,按照每个3个分割未多个list
List<List<String>> newList = splitList(idList, 3);
//创建连接池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 1l, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());
//记录单个任务的执行次数
CountDownLatch countDownLatch = new CountDownLatch(newList.size());
//对拆分的集合进行批量处理
for (List<String> childList : newList) {
threadPool.execute(new Thread(() -> {
HBSession session = HBUtil.getHBSession();
childList.forEach(id->{
//往数据库中新增id数据 伪代码
});
// 任务个数 - 1, 直至为0时唤醒await()
countDownLatch.countDown();
}));
}
// 让当前线程处于阻塞状态,直到锁存器计数为零
countDownLatch.await();
System.out.println("新增完成");
//执行其他代码
}