簡體   English   中英

如何殺死子線程啟動的進程?

[英]How to kill a process which is started by child thread?

碼:

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 如果我做了final ,我不能在這里指定價值。 p= Runtime.getRuntime().exec(my_CMD); 請幫助。

Process API已經有了解決方案。 當你嘗試在進程上調用destroy()時發生了什么? 當然假設您已經更改了上面的代碼並將Process變量p聲明為類字段。

Runtime.getRuntime().exec(...)說一句,你應該避免使用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();
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM