2013-04-09 48 views
0

嗨,我想知道如何使用計時器來銷燬一個進程,如果它經過了毫秒級的預定義時間段。使用定時器摧毀/中斷Java中的進程

目前我有從運行時獲取線程的方法

Runtime runtime = Runtime.getRuntime(); 

我然後創建單獨的進程使用運行時

Process process = runtime.exec(comman); //where command is a string with a defined command 
執行命令

我然後處理正常/錯誤輸出流致電前:

process.waitFor(); 

這等待進程終止if它還沒有。

我的問題是,我該怎麼去使用定時器終止進程之前已經完成,即通過調用:

process.destroy; 

基本上,如果工藝作品超過一定的時間長度,我想過早地銷燬它。

如果由於過度運行而被銷燬,我會拋出InterruptedException。

有人告訴我,使用計時器將是實現這一目標的最佳方法,但並不確定是否如此?

任何幫助將非常感激。

+0

這個線程似乎是一個好辦法: http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread 問候 – Martin 2013-04-09 11:39:23

+0

你在問是否使用定時器的最佳解決方案,或者定時器實現的例子嗎? – icrovett 2013-04-09 11:42:46

+0

如何使用計時器實現它 – 2013-04-09 13:30:55

回答

0

嘗試

final Process p = ... 
    final Thread mainThread = Thread.currentThread(); 
    Thread t = new Thread() { 
     public void run() { 
      try { 
       Thread.sleep(1000); 
       p.destroy(); 
       mainThread.interrupt(); 
      } catch (InterruptedException e) { 
      } 
     }; 
    }; 
    p.waitFor(); 
    if (mainThread.isInterrupted()) { 
     throw new InterruptedException(); 
    } 
    t.interrupt();