java方法執行超時關閉


  1. Callable<String> task = new Callable<String>() {
  2.             @Override
  3.             public String call() throws Exception{
  4.                 //執行耗時代碼
  5.                 Thread.sleep(10000);
  6.                 return "success";
  7.             }
  8.         };
  9.         ExecutorService executorService = Executors.newSingleThreadExecutor();
  10.         Future<String> future = executorService.submit(task);
  11.         try {
  12.             //設置超時時間
  13.             String rst = future.get(5,TimeUnit.SECONDS);
  14.             System.out.println(rst);
  15.         } catch (TimeoutException e) {
  16.             System.out.println("執行超時");
  17.         } catch(Exception e){
  18.             System.out.println("獲取數據異常," + e.getMessage());
  19.         }finally {
  20.             executorService.shutdown();
  21.         }


免責聲明!

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



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