java中ExecutorService使用多線程處理業務


 

1,定義線程對象

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM