如何杀死子线程启动的进程?

shr*_*yak 5 java scope

码:

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.
Run Code Online (Sandbox Code Playgroud)

我怎么能用Java做到这一点?如果我把它作为一个类字段,就像在

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.
Run Code Online (Sandbox Code Playgroud)

因为它在一个线程中,所以它要求我将Process P设为final.如果我这样做final,我不能在这里指定价值.p= Runtime.getRuntime().exec(my_CMD);.请帮助.

Hov*_*els 3

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

顺便说一句,您应该避免使用Runtime.getRuntime().exec(...)来获取 Process,而应该使用 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();
  }
}
Run Code Online (Sandbox Code Playgroud)