父母thead停止时退出java process.exec

时间:2014-07-28 13:54:01

标签: java multithreading process

我有一个java应用程序,它创建一个调用Process.exec来启动python程序的线程。但是当我退出程序时,java线程将停止,但我的python进程继续运行。当我停止执行java文件时,有没有办法停止python进程?

这是代码的片段,它启动新线程,然后开始执行python脚本。

MyRunnable myRun = new MyRunnable();
Thread myThread = new Thread(myRun);
myThread.start();

myRunable.java类如下

public class myRunnable implements Runnable(){
    public myRunnable(){

    }
public void run(){
    try{
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("python myPythonScript.py");
        StreamGobbler errGobber = new StreamGobbler(proc.getErrorStream(), "Error");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
        errgobbler.start()
        outpoutGobbler.start()
    }catch (IOException e){
        e.printStackTrace();
    }
   }
}

当我退出java应用程序时,线程停止运行,但是我的python脚本将继续在单独的进程中执行。我想在线程退出时停止这个过程。

编辑: 我开始玩Runtime.addShutdownHOok(),如下所述。我还在测试它,以确保它按照我的预期工作,但到目前为止它似乎正在工作。我编辑了Runnable类以包含shutdownHook,如下所示:

public void run(){
    try{
        Runtime rt = Runtime.getRuntime();
        final Process proc = rt.exec("python myPythonScript.py");
        rt.addShutdownHOok(new Thread(){
            public void run(){
                System.out.println("Exit process");
                proc.destroy();
            }
        )};
        StreamGobbler errGobber = new StreamGobbler(proc.getErrorStream(), "Error");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
        errgobbler.start()
        outpoutGobbler.start()
    }catch (IOException e){
        e.printStackTrace();
    }
   }
}    

1 个答案:

答案 0 :(得分:0)

Runtime.exec()会返回Process个对象。您可以使用它来终止外部应用程序:

Process p = Runtime.getRuntime().exec(command);
p.destory();