2014-01-16 75 views

回答

3

隨着執行人及期貨的幫助,我認爲這可能幫助

ExecutorService executor = Executors.newCachedThreadPool(); 

    Future<String> future = executor.submit(new Callable<String>() { 
     public String call() throws Exception { 
      return someVeryLengthMethod(); 
     }}); 

    String result = null; 
    try { 
     result = future.get(2, TimeUnit.MINUTES); 
    } catch (InterruptedException e) { 
     // Somebody interrupted us 
    } catch (ExecutionException e) { 
     // Something went wring, handle it... 
    } catch (TimeoutException e) { 
     // Too long time 
     future.cancel(true); 
    } 
    // Continue with what we have... 

這將等待答案指定的ti如果在這段時間內結果不可用,未來將被取消(這可能會或可能不會實際停止執行該任務),並且代碼可以繼續。

6

使用jcabi API已經爲這種事情非常有益的:jcabi API

非常漂亮的基於註解的API,所以在你的情況下,它會像這樣工作:

@Timeable(limit = 120, unit = TimeUnit.SECONDS) 
public void methodYouWantToTime(){...} 
4

的組合以下可能的工作:

時間跟蹤:

// use this to record when a process started 
long start = System.currentTimeMillis(); 
// subsequent calls can be used to track how long something has been running? 
long timeInMillis = System.currentTimeMillis() - start; 

級獨立的進程:

java.lang.Thread // Extend this class 
// And implement your own run() method. 

在這種等待單獨的線程來完成的循環,你可以使用:

Thread.interrupt(); // This method could then be used to stop the execution 
Thread.stop(); // This is also another way to stop execution, but it is deprecated and its use is frowned upon! 

HTH

0

這個問題是在不同的線程中解釋。最好的方法是使用帶有超時的ThreadPool(請參閱ExecutorService)。

例,提交任務並等待60秒的回答:

ExecutorService pool = Executors.newCachedThreadPool(); 
    Future<Object> future = pool.submit(new Callable<Object>() { 
     @Override 
     public Object call() throws Exception { 
      Thread.sleep(1000); 
      return this; 
     } 
    }); 
    Object result = future.get(60, TimeUnit.SECONDS); 

如果你想等待一個任務的完成,但你不希望任何輸出,更好地利用:

pool.submit(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       Thread.sleep(10000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
    // Wait until the task is completed, then shut down the pool 
    pool.awaitTermination(60, TimeUnit.SECONDS); 

本線程中的更多細節:ExecutorService that interrupts tasks after a timeout

相關問題