java中ExecutorService使用多线程处理业务

  • 1:定义线程对象Callable:Callable可以看成是一个增强版的Runnable, 带返回结果, 需要通过Future或者FutureTask来提交任务或运行线程, 然后通过Future/FutureTask的get方法得到返回结果.
    Callable在子线程中运行, 在主线程中通过Future或者FutureTask来异步得到执行结果(get()方法是阻塞的), 或者检查是否已取消, 是否已完成(检查取消和完成的方法是非阻塞的)。
class CancelApprovalCallable implements Callable<JSONbject>{
        
        private String id;
        private String domain;
        CancelApprovalCallable(String id,String domain){
            this.id=id;
            this.domain = domain;
        }
        /* (non-Javadoc)
         * @see java.util.concurrent.Callable#call()
         */
        @Override
        public JSObject call() throws Exception {
            
            return null;
        }
        
    }
  • 2:使用线程池执行多线程
ExecutorService executorService = Executors.newFixedThreadPool(5);  
  
List<CancelApprovalCallable> callables = new List<>();  
for(int i=0,len=idsArray.size();i<len;i++){
    String id = idsArray.get(i);
    CancelApprovalCallable callable = new CancelApprovalCallable(id,domain);
    callables.add(callable);
}
List<Future<JSONObject>> resultList = new ArrayList<>();
try{
    resultList = executorService.invokeAll(callables);
    //ExecutorService.invokeAll(Collection<Callable> tasks)能够批量提交任务,
    //但是该方法只有在tasks全部执行完毕才返回包含各个任务对应的Future实例的列表。
    //因此invokeAll方法批量提交任务的时候,
    //任务等待返回结果的时间取决于这批任务中最耗时的任务。
}catch(InterruptedException e){
    log.error("execute concurrent thread error",e);
}finally{
    if(!executorService.isShutdown() || !executorService.isTerminated()){
        executorService.shutdown();
    }
}

ExecutorCompletionService中使用take()可以先获取任务已经执行完成的结果,而不需要等待所有任务执行完毕,但是假如没有一个任务执行完成也会阻塞获取结果。

  • 3:获取执行结果
/**
*批量获取线程执行结果,循环处理每条结果数据
*/
for(Future<JSONObject> future : resultList){
    JSONObject resp2 = null;
    try{
        resp2 = future.get();//假如任务未完成,会阻塞获取结果
    }catch(Exception e){
        log.error("execute concurrent thread error",e);
    }
    if(resp2 == null){
        continue;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值