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

前端之家收集整理的这篇文章主要介绍了java – 如何杀死由子线程启动的进程?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
码:
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.

我怎么能用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.

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

解决方法

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();
  }
}

猜你在找的Java相关文章