多线程操作List

多线程操作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;
    }
}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值