大集合批量操作(集合拆分+多线程处理)

当需要对一个集合中有一千或者一万的数据需要进行操作时,单线程会降低效率,为了提高执行效率,可以将该集合分割为多个小集合,然后利用多线程进行批量同步运行,提高效率。

1、集合拆分工具类

	/*** 拆分list集合 (后期如果使用次数多,可将其封装在工具类中)* 可将给定old集合根据sublength大小分割为多个 集合大小为 sublength的集合* @param oldList 需要拆分的集合* @param subLength 拆分的大小* @return* @param */private static  List> splitList(List oldList, int subLength){ArrayList> returnList = new ArrayList<>();ArrayList 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个集合,每个大小subLengthfor (int i = 0; i < pre; i++) {ArrayList 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 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 idList) throws AppException, InterruptedException {//将ids进行分割,按照每个3个分割未多个listList> 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 childList : newList) {threadPool.execute(new Thread(() -> {HBSession session = HBUtil.getHBSession();childList.forEach(id->{//往数据库中新增id数据  伪代码});// 任务个数 - 1, 直至为0时唤醒await()countDownLatch.countDown();}));}// 让当前线程处于阻塞状态,直到锁存器计数为零countDownLatch.await();System.out.println("新增完成");//执行其他代码}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部