java多次嵌套循环查询数据库导致代码中数据处理慢的解决
业务现象
代码中有一部分代码多次嵌套循环和数据处理,执行速度很慢
解决方案
通过多线程
1、启用多线程
private final static Executor executor = Executors.newFixedThreadPool(3);
2、初始化设置count
即等待(await)count个线程或一个线程count次计数,通过工作线程来countDown计数减一,直到计数为0,await阻塞结束;目的:保证所有线程都走完
final CountDownLatch latch = new CountDownLatch(dataList.size());
3、需要重新run
需要多线程的代码写在run中
@Override
public void run() {
//业务代码处理
//countDown计数减一
latch.countDown();
}
4、阻塞线程
// 等待所有工作线程结束
latch.await();
关键代码
private final static Executor executor = Executors.newFixedThreadPool(3);//启用多线程
public Result getList(@RequestBody StatusDbSelectParam param){
PageHelper.startPage(param.getPageNum(), param.getPageSize());
List<Map<String, Object>> dataList = statusDbService.selectByTime(tableName, columnNames.toString(), param.getStartTime(), param.getEndTime());
//初始化设置count,即等待(await)count个线程或一个线程count次计数,通过工作线程来countDown计数减一,直到计数为0,await阻塞结束
final CountDownLatch latch = new CountDownLatch(dataList.size());
for(int k =0;k<dataList.size();k++) {
final int i = k;
String finalTableName = tableName;
executor.execute(new Runnable() {
@Override
public void run() {
try {
Map<String, Object> map = dataList.get(i);
for (String pid : map.keySet()) {
String val = String.valueOf(map.get(pid));
String columPid = pid.substring(2, pid.length()).toLowerCase();
List<MonitorRuleEntity> list = monitorRuleService.listMonitorRule(columPid, finalTableName);
String status = "";
//循环规则数据 判断监测点是否报警 更新状态
for (int j = 0; j < list.size(); j++) {
Boolean flag = DevHealthStatusFactory.getInstance().getResultMapByRule(val, list.get(j));
if (flag) {
if (j == 0) {
status = "A";
break;
} else if (j == 1) {
status = "B";
break;
} else if (j == 2) {
status = "C";
break;
}
}
}
if (pid.equalsIgnoreCase(timeColumnName)) {
map.put(pid, val);
} else {
map.put(pid, val + "_" + status);
}
}
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
try {
// 等待所有工作线程结束
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return ResultMsg.succeSSMsg().data(new PageInfo<>(dataList));
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
相关文章