通过对业务逻辑的分析,进行编码,先把第一条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,结果项目跑不下去被投诉了。
请各位大神不吝赐教,小白在此谢过了。