【问题标题】:How to kill a process which is started by child thread?如何杀死由子线程启动的进程?
【发布时间】:2013-07-20 17:41:09
【问题描述】:

代码:

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.

由于它在线程中,它要求我将进程 P 设为final。如果我这样做final,我不能在这里赋值。 p= Runtime.getRuntime().exec(my_CMD); 。请帮忙。

【问题讨论】:

  • 见编辑回答。同样,您的 p 变量是该方法的本地变量。不要那样做——让它成为一个类字段。
  • @HovercraftFullOfEels 感谢您指出这一点。只是假设它是一个类字段。谢谢

标签: java scope


【解决方案1】:

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

【讨论】:

  • 他已经在run() 内部定义了进程变量——在t.start() 之后外部无法调用destroy()。
  • @BimaleshJha:我已与您的评论同步编辑了我的答案。这只是范围问题,但希望如果他以这种方式调用外部代码,他会理解范围规则,否则他可能会本末倒置。
  • 在更高的范围内,我认为,流程变量 p 必须声明为 final?
  • @BimaleshJha:是的,因为它被用于匿名内部类。要么将其声明为类字段。但同样,这不过是基本的 Java。
  • 最初的问题让我感到困惑的是,为什么原始发布者在来这里之前没有先看一下 API?答案很容易在几分之一秒内从该资源中获得。
猜你喜欢
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多