2017-01-22 49 views
2

我有一些方法叫做exampleMethod。 當我打電話這種方法(它與網絡...)有些時候,當網絡慢需要很長時間...如何設置在java中執行一些方法的時間?

我怎樣才能設置一些最大時間執行?

例如10s。

就像這個...

try { 
     exampleMethod(); 
} catch(Exeption e) { 
     LoggError("I was to slow"); 
} 

我希望你理解我,謝謝您的幫助,

+0

這取決於你的方法在做什麼。通常阻塞操作會允許超時或中斷。 – shmosel

+0

可能重複的[如何超時線程](http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread) – tucuxi

+0

當然,我可以寫一些自己的超時包裝?有可能的? – rilav

回答

0

可以使用的ExecutorService,設置超時值,並取消今後如果超時被傳遞以請求線程中斷:

ExecutorService executorService = Executors.newSingleThreadExecutor(); 
    Future<?> future = null; 
    try { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       while (true) { 
        // it the timeout happens, the thread should be interrupted. Check it to let the thread terminates. 
        if (Thread.currentThread().isInterrupted()) { 
         return; 
        } 
        exampleMethod(); 
       } 

      } 
     }; 

     future = executorService.submit(r); 
     future.get(10, TimeUnit.SECONDS); 
    } 

    // time is passed 
    catch (final TimeoutException e) { 
     System.out.println("I was to slow"); 
     // you cancel the future 
     future.cancel(true); 
    } 
    // other exceptions 
    catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     executorService.shutdown(); 
    } 
} 
+1

這不會阻止任務,它會停止等待它。 – shmosel

相關問題