CountDownLatch的使用例子

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();
}

}
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值