java多次嵌套循環(huán)查詢數(shù)據(jù)庫導致代碼中數(shù)據(jù)處理慢的解決
更新時間:2023年03月15日 09:22:44 作者:念舊、sunshine
這篇文章主要介紹了java多次嵌套循環(huán)查詢數(shù)據(jù)庫導致代碼中數(shù)據(jù)處理慢的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
業(yè)務(wù)現(xiàn)象
代碼中有一部分代碼多次嵌套循環(huán)和數(shù)據(jù)處理,執(zhí)行速度很慢
解決方案
通過多線程
1、啟用多線程
private final static Executor executor = Executors.newFixedThreadPool(3);
2、初始化設(shè)置count
即等待(await)count個線程或一個線程count次計數(shù),通過工作線程來countDown計數(shù)減一,直到計數(shù)為0,await阻塞結(jié)束;目的:保證所有線程都走完
final CountDownLatch latch = new CountDownLatch(dataList.size());
3、需要重新run
需要多線程的代碼寫在run中
?@Override
? ? ? ?public void run() {?
? ? ? ? ? ? ? ? //業(yè)務(wù)代碼處理
? ? ? ? ? ? ? ? //countDown計數(shù)減一
? ? ? ? ? ? ? ? ?latch.countDown();
}4、阻塞線程
? // 等待所有工作線程結(jié)束 ? ? ? ? ? ? latch.await();
關(guān)鍵代碼
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());
//初始化設(shè)置count,即等待(await)count個線程或一個線程count次計數(shù),通過工作線程來countDown計數(shù)減一,直到計數(shù)為0,await阻塞結(jié)束
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 = "";
//循環(huán)規(guī)則數(shù)據(jù) 判斷監(jiān)測點是否報警 更新狀態(tài)
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 {
// 等待所有工作線程結(jié)束
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return ResultMsg.successMsg().data(new PageInfo<>(dataList));
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot如何使用Undertow做服務(wù)器
這篇文章主要介紹了SpringBoot如何使用Undertow做服務(wù)器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
IntelliJ IDEA下SpringBoot如何指定某一個配置文件啟動項目
這篇文章主要介紹了IntelliJ IDEA下SpringBoot如何指定某一個配置文件啟動項目問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
SpringBoot整合mybatis使用Druid做連接池的方式
這篇文章主要介紹了SpringBoot整合mybatis使用Druid做連接池的方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08

