1. 程式人生 > >spring+mybatis 多執行緒訪問資料

spring+mybatis 多執行緒訪問資料

在做大資料量查詢的時候,想到了用多執行緒,各執行緒之間沒有聯絡,各走各的業務邏輯,節省了很多時間

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---------");