业务场景:前端调Java接口,接口需要多次请求http请求,因为是顺序执行,每个http耗时很长,大概5秒左右,但是叠加起来是很恐怖的,有必要做成多线程去处理。
大体思路:多线程去do任务,使用CountDownLatch进行计数当前线程执行结束,然后调用await()方法,继续向下执行
上代码:
public String picMark(Model model, HttpServletRequest request) throws Exception {
Map<String,Object> paramPicMap = picAssessService.getParamPic();//查库
CountDownLatch latch=new CountDownLatch(2);
Worker worker1=new Worker("DAMO", latch,paramPicMap);//走http比较慢
Worker worker2=new Worker("YUSHI", latch,paramPicMap);//走http比较慢
worker1.start();//
worker2.start();//
//步骤3、4、调用await放过,等待所有线程完成工作
latch.await();
if(worker1.resultList == null && worker2.resultList == null ){
model.addAttribute("message","暂无可标注的数据");
}
model.addAttribute("picAssessList",worker1.resultList);
model.addAttribute("newPicAssessList",worker2.resultList);
model.addAttribute("paramPicUrl",paramPicMap.get("url"));
return "modules/beyond/picAssess/picAssessForm";
}
class Worker extends Thread{
CountDownLatch latch;
String algorithmType;
List resultList;
Map<String,Object> paramPicMap;
public Worker(String algorithmType,CountDownLatch latch,Map<String,Object> paramPicMap){
this.algorithmType=algorithmType;
this.latch=latch;
this.paramPicMap=paramPicMap;
}
@Override
public void run(){
doWork(algorithmType,paramPicMap);//工作逻辑方法
latch.countDown();//每完成一次减1
}
private void doWork(String algorithmType,Map<String,Object> paramPicMap){
try {
if("DAMO".equals(algorithmType)){
this.resultList=picAssessService.getSearchPicList(paramPicMap);//实际需要走http的方法,很耗时
}else if("YUSHI".equals(algorithmType)){
this.resultList=picAssessService.getNewSearchPicList(paramPicMap);//实际需要走http的方法,很耗时
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用后耗时减少了近一倍,当http越多节省的时间越多!!