標籤:線程池 executorservice callable future 執行方法逾時
今天在項目開發中需要用到對執行方法加上時間控制,如果方法執行過長則跳出執行,廢話不說,直接上代碼,用的是線程池配合Callable和Future方式對執行方法的逾時阻斷。希望各位牛人指正
//啟用線程池 final ExecutorService exec = Executors.newFixedThreadPool(1); Callable<Map<String, String>> call = new Callable<Map<String, String>>(){ public Map<String, String> call() throws Exception { Map<String,String> excuteMap = new HashMap<String,String>(); excuteMap = sendSSHSYS(servicePC, arrPort);//在這裡執行相應的商務邏輯,要注意call裡使用的參數是final的 return excuteMap; } }; Future<Map<String, String>> future = exec.submit(call); try { //20秒逾時,這裡是取出call中的傳回值,如果在時間內仍然沒有執行完畢的話,返回null map=future.get(20, TimeUnit.SECONDS); } catch (InterruptedException e) { } catch (ExecutionException e) { } catch (TimeoutException e) { } //在這下面就可以對map進行處理,如果map是null就說明是執行時間過長而阻斷了。
java利用線程池(ExecutorService)配合Callable和Future實現執行方法逾時的阻斷