多线程操作List场景,一般是List对象太大需要拆分处理。或者是多个list中需要取同一个属性值。每个处理过程时间比较长,这时候可以使用多线程来加快处理效率。如果是处于非事务的操作场景,那可以直接每个线程单独逻辑处理,最终汇总。如果是事务的操作场景,则再对数据库操作前设置事务手动提交,然后用submit提交任务,Feature获取每个线程的执行结果。如果成功,在一次性提交事务,失败回退事务。
下面是一段模板代码,多个线程去计算list的数值。可以参照此模板改造适配其他业务场景。其主要逻辑
1.使用SplitListUtils拆分list
2.使用CountDownLatch阻塞主线程等待多个任务的执行结果
3.线程池使用submit执行任务,获取每个任务的结果。这里也可以使用invokeAll().
4.处理每个结果进行运算。
/**
* 多线程处理List
*/
@Slf4j
public class ThreadList {
public static void main(String[] args) throws InterruptedException {
AtomicInteger atomicIntegerAll = new AtomicInteger(0);
List<Child> childList = generChildList(10000);
List<List<Child>> split = SplitListUtils.split(childList, 1000);//拆分10个子list
ExecutorService executorService = new ThreadPoolExecutor(10,10,100,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(1));
CountDownLatch countDownLatch = new CountDownLatch(10);
List<Future<Integer>> futureList = new ArrayList<>();
for (List<Child> children:split){
Future<Integer> submit = executorService.submit(()-> {
AtomicInteger sum = new AtomicInteger(0);
for (int i = 0;i<children.size();i++){
sum.getAndAdd(children.get(i).getNum());
}
log.info("计数{}", sum.get());
return sum.get();
});
futureList.add(submit);
countDownLatch.countDown();
}
countDownLatch.await();
futureList.forEach(integerFuture -> {
try {
atomicIntegerAll.getAndAdd(integerFuture.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
log.info("计数{}", atomicIntegerAll.get());
executorService.shutdown();
}
/**
* 生成LIST
* @param num
* @return
*/
public static List<Child> generChildList(int num){
List<Child> childList = new ArrayList<>();
for (int i =0 ; i <num ; i++){
Child child = new Child();
child.setNum(i);
childList.add(child);
}
return childList;
}
工具类
/**
* 拆分结合工具类
*/
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 new ArrayList();
}
List<List<T>> ret = new ArrayList();
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 = new ArrayList();
for (int j = 0; j < subListLength; j++) {
itemList.add(resList.get(i * subListLength + j));
}
ret.add(itemList);
}
// last的进行处理
if (last > 0) {
List<T> itemList = new ArrayList();
for (int i = 0; i < last; i++) {
itemList.add(resList.get(pre * subListLength + i));
}
ret.add(itemList);
}
}
return ret;
}
}