java多次嵌套循環(huán)查詢數(shù)據(jù)庫導(dǎo)致代碼中數(shù)據(jù)處理慢的解決
更新時間:2023年03月15日 09:22:44 作者:念舊、sunshine
這篇文章主要介紹了java多次嵌套循環(huán)查詢數(shù)據(jù)庫導(dǎo)致代碼中數(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)文章
ShardingSphere jdbc實現(xiàn)分庫分表核心概念詳解
這篇文章主要為大家介紹了ShardingSphere jdbc實現(xiàn)分庫分表核心概念詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12Spring boot集成redis lettuce代碼實例
這篇文章主要介紹了Spring boot集成redis lettuce代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04關(guān)于Sentinel中冷啟動限流原理WarmUpController
這篇文章主要介紹了關(guān)于Sentinel中冷啟動限流原理WarmUpController,具有很好的參考價值,希望對大家有所幫助。2023-04-04