2011-04-27 89 views
1

我想在x秒後停止該方法。 我該怎麼做?在java中爲方法創建超時的最佳方式是什麼?

編輯
我會詳細說明: 我的方法()是本地的或與其他服務器通信。
我不在一個循環(因此我不能改變一個標誌) 我會想要使用方法的返回值,如果它存在。

+5

請參閱http://stackoverflow.com/questions/2733356/killing-thread-after-some-specified-time-limit-in-java – armandino 2011-04-27 06:35:59

回答

2

,在很大程度上取決於你的方法做。最簡單的方法是定期檢查方法執行的時間,並在超出限制時返回。

long t0 = System.currentTimeMillis(); 
// do something 
long t1 = System.currentTimeMillis(); 
if (t1-t0 > x*1000) { 
    return; 
} 

如果你想運行在一個單獨的線程的方法,那麼你可以做這樣的事情:

public <T> T myMethod() { 
    ExecutorService executor = Executors.newSingleThreadExecutor(); 
    try { 
     try { 
      T value = executor.invokeAny(Collections.singleton(new Callable<T>() { 
       @Override 
       public T call() throws Exception { 
        //your actual method code here 
        return null; 
       } 
      }), 3, TimeUnit.SECONDS); 
      System.out.println("All went fine"); 
      return value; 
     } catch (TimeoutException e) { 
      System.out.println("Exceeded time limit, interrupted"); 
     } catch (Exception e) { 
      System.out.println("Some error happened, handle it properly"); 
     } 
     return null; /*some default value*/ 
    } finally { 
     executor.shutdownNow(); 
    } 
} 

請注意,如果你在線程中做一些未中斷IO ,此方法將無法工作。

+0

我可以使用mt方法返回值?像Callable ? – Jeb 2011-04-27 07:07:14

+0

@ user450602是,invokeAny方法返回返回值(請參閱http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html)。 – dacwe 2011-04-27 07:18:06

+0

@ user450602請檢查更新後的答案 – 2011-04-27 07:25:56

0

這取決於你在做什麼以及你需要的準確度。 如果你在循環中,你可以跟蹤使用System.currentTimeMillis()已經過了多少時間。只要開始時間,並定期檢查並瞭解已過多久。

你可以產生一個新的線程來開始你的處理,睡眠x秒,然後做一些事情來停止處理線程。

+0

循環將無法正常工作,假設您是使用網絡連接,甚至單線可能需要開銷時間 – 2011-04-27 07:00:10

1

最可靠的方法 - 就我看來 - 是一個多線程解決方案。我會將長時間運行的算法放在Runnable中,並使用ExecutorService來執行給定超時的線程。

回答this question提供瞭解決方案的更多細節。

當然,現在的方法將在平行exectued主線程,但你可以強制單個線程的行爲Thread#join - 只需用你的主線程等到有時間限制的工作線程完成或超過它的超時限制。

0

你不能這樣做,在一次執行必須使用螺紋爲

我同意armandino

see this

相關問題