spring+mybatis 多线程访问数据

来源:互联网 发布:小白网络技术论坛 编辑:程序博客网 时间:2024/06/11 00:32

在做大数据量查询的时候,想到了用多线程,各线程之间没有联系,各走各的业务逻辑,节省了很多时间


ThreadPoolExecutor executor = new ThreadPoolExecutor(5,8, 3000, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(2000));

LinkedBlockingQueue<Runnable> queue = (LinkedBlockingQueue<Runnable>) executor.getQueue();
int countTool= agencyids.size();
final CountDownLatch countDownLatch = new CountDownLatch(countTool);

for(AgencyPO agency:agencyids){
final AgencyPO po  = agency;
final Service outService = service; //service为spring注入 
final HashMap param = new HashMap(); //传的参数,这里一定要注意,一定要在循环里面重新建参数map,否则会导致线程里调用map有问题

executor.execute(new Runnable(){

public void run() {
   
try {

param.put("agency", po.getGuid());
List<Map<String, Object>> list = outService.getResult(param);//调用service层的一个方法



} catch (Exception e) {

e.printStackTrace();
}
countDownLatch.countDown();
}
});
}
//所有子线程 执行完成之后 主线程再继续向下 
countDownLatch.await();
System.out.println("------------- end---------");