第一次使用ThreadPoolExecutor处理业务

通过对业务逻辑的分析,进行编码,先把第一条sql查出来的数据进行分组,然后分别使用不同的线程去查询数据返回,并添加到原来的数据中。

总感觉哪里写的不对,但是同事们都没用过这个,请大家指教一下,先谢谢了。

java 复制代码
private List<Map<String,Object>> getData(List<Map<String,Object>> dataList) throws InterruptedException {
       CountDownLatch countDownLatch = new CountDownLatch(4);
       //将dataList截断分成4组
       int size = dataList.size();
       int groupCount = size / 4;
       List<Map<String,Object>> dataList1 =new ArrayList<>(dataList.subList(0, groupCount));
       List<Map<String,Object>> dataList2 =new ArrayList<>(dataList.subList(groupCount, groupCount*2));
       List<Map<String,Object>> dataList3 =new ArrayList<>(dataList.subList(groupCount*3, groupCount*4));
       List<Map<String,Object>> dataList4 =new ArrayList<>(dataList.subList(groupCount*4, size));
       ThreadPoolExecutor poolExecutor = creatThread("getData", 4);
       threadTask(poolExecutor,dataList1,countDownLatch);
       threadTask(poolExecutor,dataList2,countDownLatch);
       threadTask(poolExecutor,dataList3,countDownLatch);
       threadTask(poolExecutor,dataList4,countDownLatch);
       while (countDownLatch.getCount() != 0){
           countDownLatch.await();
       }
       dataList.clear();
       List<Map<String,Object>> newDataList = new ArrayList<>();
       newDataList.addAll(dataList1);
       newDataList.addAll(dataList2);
       newDataList.addAll(dataList3);
       newDataList.addAll(dataList4);
       return newDataList;
   }

具体逻辑代码:

java 复制代码
 private  void threadTask(ThreadPoolExecutor threadPoolExecutor,final List<Map<String,Object>> dataList,final CountDownLatch countDownLatch){
        Callable<List<Map<String,Object>>> getData=new Callable<List<Map<String, Object>>>() {
            @Override
            public List<Map<String, Object>> call() {
                for (Map<String, Object> stringObjectMap : dataList) {
                    //执行的方法
                }
                countDownLatch.countDown();
                return dataList;
            }
        };
       FutureTask<List<Map<String,Object>>> getDataTask = new FutureTask<>(getData);
       threadPoolExecutor.execute(getDataTask);
   }

这里还是用原生的方法,没有使用lambda,因为服务器上的Jdk不确定是7还是8,上次有同事使用了stream去处理list,结果项目跑不下去被投诉了。

请各位大神不吝赐教,小白在此谢过了。

相关推荐
liu_chunhai3 分钟前
设计模式(3)builder
java·开发语言·设计模式
ya888g39 分钟前
GESP C++四级样题卷
java·c++·算法
【D'accumulation】1 小时前
令牌主动失效机制范例(利用redis)注释分析
java·spring boot·redis·后端
小叶学C++1 小时前
【C++】类与对象(下)
java·开发语言·c++
2401_854391081 小时前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
Cikiss1 小时前
微服务实战——SpringCache 整合 Redis
java·redis·后端·微服务
wxin_VXbishe1 小时前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
Cikiss1 小时前
微服务实战——平台属性
java·数据库·后端·微服务
无敌の星仔1 小时前
一个月学会Java 第2天 认识类与对象
java·开发语言
OEC小胖胖1 小时前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web