Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何终止由子线程启动的进程?_Java_Scope - Fatal编程技术网

Java 如何终止由子线程启动的进程?

Java 如何终止由子线程启动的进程?,java,scope,Java,Scope,代码: 我如何在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. 因为它在一个线程中,所以它要求我将进程p设为

代码:

我如何在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.
因为它在一个线程中,所以它要求我将进程p设为
final
。如果我将该
设为最终值
,则无法在此处赋值
p=Runtime.getRuntime().exec(my_CMD)。plz帮助。

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

另外,您应该避免使用
Runtime.getRuntime().exec(…)
来获取流程,而应该使用ProcessBuilder。另外,当可以实现Runnable时,不要扩展线程

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()
中定义了流程变量-在
t.start()
调用destroy()之后,该变量在外部不可用。@bimaleshja:我已将我的答案与您的注释同步编辑。这只是范围的问题,但如果他以这种方式调用外部代码,希望他理解范围规则,否则他可能是本末倒置。在更高的范围内,我认为,进程变量p必须声明为final?@BimaleshJha:是的,因为它被用于匿名内部类中。或者将其声明为类字段。但同样,这只不过是基本的Java。让我困惑的是,为什么最初的海报在来到这里之前没有先看API?答案可以在几分之一秒内从该资源中轻松获得。请参阅编辑以获得答案。同样,p变量是方法的局部变量。不要这样做——将其设为类字段。@HovercraftFullOfEels感谢您指出这一点。只是假设它是一个类字段。谢谢
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();
  }
}