CountDownLatch是主线程等待一堆子线程执行完之后,主线程在往下执行
例子:
public List<RebotEntity> getRebotList(QueryRebotDto queryRebotDto) throws InfrastructureException{
List<RebotEntity> rebotList=new ArrayList<RebotEntity>();
try{
String ips=“http://10.172.145.182:8855/&730;http://10.132.177.4:8855/&123;http://10.47.18.145:8855/&234;http://10.34.19.134:8855/&567;http://10.150.143.66:8855/&567”;
String[] ipsarry=ips.split(";");
int length=ipsarry.length;
CountDownLatch latch=new CountDownLatch(length);
LinkedBlockingQueue<String> batchQueue = new LinkedBlockingQueue<String>(); //实例一个队列
for(int i=0;i<length;i++){
batchQueue.put(ipsarry[i]);
}
ExecutorService executeService=Executors.newFixedThreadPool(length); //实例一个线程池
for(int i=0;i<length;i++){
String[] app_ids=ipsarry[i].split("&");
QueryRebotDto Rebot=new QueryRebotDto();
Rebot.setLimit(queryRebotDto.getLimit());
Rebot.setStart(queryRebotDto.getStart());
Rebot.setSteamId(queryRebotDto.getSteamId());
Rebot.setSteamName(queryRebotDto.getSteamName());
Rebot.setApp_id(app_ids[1]);
Task tasks = new Task(batchQueue,Rebot,rebotList,latch);
executeService.execute(tasks); //执行线程
}
logger.error("等待"+length+"个线程执行完毕....");
latch.await(); //主线程等待子线程执行完毕
logger.error(length+"个线程执行完毕....");
executeService.shutdown();
}catch(Exception e){
e.printStackTrace();
}
logger.error(rebotList.size());
return rebotList; //等所有子线程都执行完之后再返回list
}
private class Task implements Runnable{
private QueryRebotDto queryRebotDto;
private LinkedBlockingQueue<String> BatchQueue;
private List<RebotEntity> list;
private CountDownLatch latch;
public Task(LinkedBlockingQueue<String> bQueue,QueryRebotDto dto,List<RebotEntity> st,CountDownLatch ch){
this.BatchQueue=bQueue;
this.queryRebotDto=dto;
this.list=st;
this.latch=ch;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
String ipAndApp=BatchQueue.take();
String[] iparray=ipAndApp.split("&");
String ip=iparray[0];
logger.error(ip+"--"+queryRebotDto.getApp_id()+"线程正在执行");
List<RebotEntity> rebotList=(List<RebotEntity>)dao.findForList("JurisdictionMapper.getRebotListByAppId", queryRebotDto);
logger.error(queryRebotDto.getApp_id()+"查询出来的数据为"+rebotList.size());
list.addAll(rebotList);
logger.error(ip+"--"+queryRebotDto.getApp_id()+"执行完毕");
latch.countDown();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}