多线程处理一个大的list
1.集合切分工具类
public class SplitListUtils { /** * 拆分集合 * * @param <T> 泛型对象 * @param resList 需要拆分的集合 * @param subListLength 每个子集合的元素个数 * @return 返回拆分后的各个集合组成的列表 * 代码里面用到了guava和common的结合工具类 **/ public static <T> List<List<T>> split(List<T> resList, int subListLength) { if (CollectionUtils.isEmpty(resList) || subListLength <= 0) { return Lists.newArrayList(); } List<List<T>> ret = Lists.newArrayList(); int size = resList.size(); if (size <= subListLength) { // 数据量不足 subListLength 指定的大小 ret.add(resList); } else { int pre = size / subListLength; int last = size % subListLength; // 前面pre个集合,每个大小都是 subListLength 个元素 for (int i = 0; i < pre; i++) { List<T> itemList = Lists.newArrayList(); for (int j = 0; j < subListLength; j++) { itemList.add(resList.get(i * subListLength + j)); } ret.add(itemList); } // last的进行处理 if (last > 0) { List<T> itemList = Lists.newArrayList(); for (int i = 0; i < last; i++) { itemList.add(resList.get(pre * subListLength + i)); } ret.add(itemList); } } return ret; } }
2.多线程演示代码
List<List<String>> splitNList = SplitListUtils.split(titles, 20); CountDownLatch countDownLatch = new CountDownLatch(splitNList.size()); BlockingQueue<Future<Map<String,List<CblWorksHistory>>>> queue = new LinkedBlockingQueue<>(); Set<String> articleTitleSet = new HashSet<>(); Set<String> videoTitleSet = new HashSet<>(); for (List<String> singleList : splitNList) { // 线程池执行 Future<Map<String,List<CblWorksHistory>>> future = threadPoolExecutor.submit(() -> { for (String title : singleList) { //此处进行业务处理 } map.put("al",articleList); map.put("vl",videoList); return map; }); queue.add(future); countDownLatch.countDown(); } try { // 让当前线程处于阻塞状态,直到锁存器计数为零 countDownLatch.await(); // 汇总结果 for(Future<Map<String,List<CblWorksHistory>>> future : queue) { Map<String,List<CblWorksHistory>> map = future.get(); list.addAll(map.get("al")); list1.addAll(map.get("vl")); } } catch (Exception e) { log.error("单篇稿件缓存周榜数据时出错"); }
浙公网安备 33010602011771号