第一次使用ThreadPoolExecutor处理业务

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

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

private List> getData(List> dataList) throws InterruptedException {
       CountDownLatch countDownLatch = new CountDownLatch(4);
       //将dataList截断分成4组
       int size = dataList.size();
       int groupCount = size / 4;
       List> dataList1 =new ArrayList<>(dataList.subList(0, groupCount));
       List> dataList2 =new ArrayList<>(dataList.subList(groupCount, groupCount*2));
       List> dataList3 =new ArrayList<>(dataList.subList(groupCount*3, groupCount*4));
       List> 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> newDataList = new ArrayList<>();
       newDataList.addAll(dataList1);
       newDataList.addAll(dataList2);
       newDataList.addAll(dataList3);
       newDataList.addAll(dataList4);
       return newDataList;
   }

具体逻辑代码:

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

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

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

你可能感兴趣的:(求助,分享,java,多线程)