5

Code:

main function{

Thread t =new Thread(){
     public void run(){
         Process p= Runtime.getRuntime().exec(my_CMD);
     }
};
t.start();
 //Now here, I want to kill(or destroy) the process p.

How can I do this in Java? If I make it as a class field as in

main function{
Process p;
Thread t =new Thread(){
     public void run(){
         p= Runtime.getRuntime().exec(my_CMD);
     }
};
t.start();
 //Now here, I want to kill(or destroy) the process p.

Since it is in a thread, it asks me to make the Process P as final. If I make that final, I cant assign value here. p= Runtime.getRuntime().exec(my_CMD); . plz help.

4

1 回答 1

3

Process API已经为此提供了解决方案。当您尝试调用destroy()该进程时发生了什么?当然,假设您已更改上述代码并将您的 Process 变量 p 声明为类字段。

顺便说一句,您应该避免使用Runtime.getRuntime().exec(...)来获取您的流程,而应该使用 ProcessBuilder。另外,当可以实现 Runnable 时,不要扩展 Thread。

class Foo {
  private Process p;

  Runnable runnable = new Runnable() {
    public void run() {
      ProcessBuilder pBuilder = new ProcessBuilder(...);  // fill in ...!
      // swallow or use the process's Streams!
      p = pBuilder.start();
    }
  }

  public Foo() {
    new Thread(runnable).start();
  }
}
于 2013-07-20T17:42:35.960 回答