2009-10-14 98 views
0

我有一个Java程序可以在OS中执行特定命令。我也使用Process.waitfor()(如下面的代码所示)来指示执行是否成功完成或失败。在操作系统中执行命令的Java

我的问题是,有没有其他的方式来避免使用process.waitfor(),有没有办法使用while循环,并执行某些操作,直到该过程完成?

  Runtime rt = Runtime.getRuntime(); 

     Process p = rt.exec(cmdFull); 

     BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String inStreamLine = null; 
     String inStreamLinebyLine=null; 
     while((inStreamLine = inStream.readLine()) == null) { 
      inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine; 
     } 


     try { 
      rc = p.waitFor(); 

     } catch (InterruptedException intexc) { 
      System.out.println("Interrupted Exception on waitFor: " + 
           intexc.getMessage()); 
     }  

啥子我希望做的,是这样的

  Runtime rt = Runtime.getRuntime(); 

     Process p = rt.exec(cmdFull); 

     BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String inStreamLine = null; 
     String inStreamLinebyLine=null; 
     while((inStreamLine = inStream.readLine()) == null) { 
      inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine; 
     } 


     try { 

      while ((rc = p.waitFor()) == true) { // This is made up, I don't even think it would work 
       System.out.println('Process is going on...'); 
      } 


     } catch (InterruptedException intexc) { 
      System.out.println("Interrupted Exception on waitFor: " + 
           intexc.getMessage()); 
     }  

感谢,

回答

1

也许这样的事情会工作。创建一个线程,建议使用@tschaible,然后在超时线程(这是您在代码中编写的部分)对该线程进行加入。这将是这个样子:

Thread t = new Thread(new Runnable() { 

    public void run() { 
    // stuff your code here 
    } 

}); 
t.run(); 

while (t.isAlive()) { 
    t.join(1000); // wait for one second 
    System.out.println("still waiting"); 
} 

这样做是启动代码作为一个单独的线程,然后测试,如果胎面完成每一秒。当线程结束并且不再活动时,while循环应该结束。您可能需要检查InterruptedException,但现在无法对其进行测试。

希望这会让您朝正确的方向发展。

1

你可以在启动过程之前生成一个新的线程。

新线程将负责打印出“正在进行中......”或任何需要的内容。

p.waitFor()完成后,启动进程的主线程将向新线程指示应该停止运行。

1

您可以产生一个新的thread并在线程中等待,通过共享变量定期从主线程检查等待线程是否已完成。