java利用線程池(ExecutorService)配合Callable和Future實現執行方法逾時的阻斷

來源:互聯網
上載者:User

標籤:線程池   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實現執行方法逾時的阻斷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.