本地代码优化总共分为以下四步骤:
- 遍历查询数据库
- 使用CompletableFuture将串行改为并行
- 简化代码,并引出线程安全问题
- CompletableFuture + countDownLatch + Vector
完整版代码如下
public List<ContractMan> selectContractMan() throws InterruptedException{
CountDownLatch countDownLatch = new CountDownLatch(5);
List<String> contractNumers= zhbExcelMapper.selectContractNumer();
Vector<ContractMan> man=new Vector<>();
List<List<String>> lists = averageAssign(contractNumers, 5);
for(int i=0;i<lists.size();i++){
int finalI = i;
CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
List<String> stringList = lists.get(finalI);
for(String s:stringList){
ContractMan contractMan =new ContractMan();
contractMan.setContractNumber(s);
String name= zhbExcelMapper.selectMan(s);
contractMan.setName(name);
man.add(contractMan);
}
return Boolean.TRUE;
}).whenComplete((v,e)->{
countDownLatch.countDown();
});
}
countDownLatch.await();
return man;
}