给线程指定超时时间,超时则停止线程
1 private String getRecommendCount(BaseInfo baseInfo) throws Exception{ 2 ExecutorService exec = Executors.newCachedThreadPool(); 3 // int timeout = 5; // 访问接口的时间限制 4 String terminalIds = getTerminalIds(baseInfo.getTaskInfo().getBranch()); 5 String queryDate = getQueryDate(baseInfo.getTaskInfo().getBranch()); 6 TradeCountThread task = new TradeCountThread(terminalIds, queryDate); 7 Future<String> future = exec.submit(task); 8 String taskResult = ""; 9 String failReason = null; 10 try { 11 // 等待计算结果,最长等待timeout秒,timeout秒后中止任务 12 taskResult = future.get(LIMIT_SECONDS, TimeUnit.SECONDS); 13 } catch (InterruptedException e) { 14 failReason = "主线程在等待返回结果时被中断!"; 15 } catch (ExecutionException e) { 16 failReason = "主线程等待返回结果,但任务本身抛出异常!"; 17 } catch (TimeoutException e) { 18 failReason = "主线程等待计算结果超时,因此中断任务线程!"; 19 exec.shutdownNow(); 20 } 21 exec.shutdown(); 22 log.info("taskResult : " + taskResult); 23 log.info("failReason : " + failReason); 24 return taskResult; 25 } 26 27 28 private class TradeCountThread implements Callable<String> { 29 30 private String terminalIds; 31 private String queryDate; 32 public TradeCountThread(String terminalIds, String queryDate){ 33 this.terminalIds = terminalIds; 34 this.queryDate = queryDate; 35 } 36 37 public String call() throws Exception { 38 String resultStr = ""; 39 String reqStr = "{\"verifyID\":\"getTxnCounts\",\"list\":[" 40 + terminalIds +"],\"queryTime\":'" 41 + queryDate +"'}"; 42 System.out.println("reqStr::"+reqStr); 43 try{ 44 Service service = new Service(); 45 Call call = (Call) service.createCall(); 46 call.setTargetEndpointAddress(GET_TXN_COUNT_URL); 47 call.setOperation(OPERATION_NAME); 48 resultStr = (String) call.invoke(new Object[]{reqStr }); 49 }catch(Exception e ){ 50 e.printStackTrace(); 51 throw e; 52 } 53 return resultStr; 54 } 55 }