2016-01-21 109 views
0

我有兩個不同的命令(在外部EXE文件上)由兩個字符串數組command1command2表示。我想在同一個線程中順序運行這兩個。具體來說,第一個命令執行10分鐘。如果需要更長時間,請終止並運行第二條命令。這是我正在做的。在同一過程對象上調用兩次Runtime.getRuntime.exec(命令)

public class MyRunnable implements Runnable { 
    private Process proc; 
    private String[] command1; 
    private String[] command2; 

    public MyRunnable (String[] command1, String[] command2) { 
     this.command1 = command1; 
     this.command2 = command2;  
    } 

    public void run() { 
     try { 
      proc = Runtime.getRuntime().exec(command1); 

      StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); 
      StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); 

      errorGobbler.start(); 
      outputGobbler.start(); 

      exitCode = proc.waitFor(10, TimeUnit.MINUTES); 
      if (exitCode) 
       System.out.println("Model " + modelPath + ": SUCCESSFULLY!"); 
      else { 
       System.out.println("Model " + modelPath + ": TIMED OUT!"); 
       proc = Runtime.getRuntime().exec(command2); 

       StreamGobbler errorGobbler1 = new StreamGobbler(proc.getErrorStream(), "ERROR"); 
       StreamGobbler outputGobbler1 = new StreamGobbler(proc.getInputStream(), "OUTPUT"); 

       errorGobbler1.start(); 
       outputGobbler1.start(); 

       proc.waitFor(10, TimeUnit.MINUTES); 
      }    
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      proc.destroy(); 
     } 
    } 
} 

StreamGobbler類我實現完全一樣,這裏www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html避免死鎖。通常,它的作用是讓另一個線程處理對象的輸出和錯誤流。

我不知道是否可以將兩個不同的子進程分配給與上面相同的進程對象。我發現即使在調用proc.waitFor(10, TimeUnit.MINUTES)之後,使用command1的過程仍會運行,這會在一段時間後在我的計算機上創建大量進程。如何終止第一條命令的進程?我在CentOS 7上使用Java 1.8。

在此先感謝。

+0

我應該在哪裏放?我試圖把它放在proc.waitFor(10,TimeUnit.MINUTE)之後,但它沒有幫助。 –

回答

0

在您的if如果您到達else語句該進程已超過超時,所以在您將新進程分配給proc之前,您必須首先終止前一個。有兩種方法爲proc.destroy()proc.destroyForcibly()在proc = Runtime.getRuntime().exec(command2);之前添加你的else聲明中的任何一個,它應該沒問題。

相關問題