杀死在不同类中创建的进程

时间:2013-08-05 16:21:25

标签: java process

假设我在Process课程中运行了一个程序,例如:

Process p1 = Runtime.getRuntime().exec("setup.exe");
try {
    p1.waitFor();
} catch (InterruptedException e) {
    //Whatever
}

然后我的GUI课程中还有一个取消按钮,类似于:

private void cancelButtonActionPerformed(ActionEvent e) {
    //Need to interrupt the thread from here!
    System.exit(0);
}

简单地退出程序就像我在Process.java运行中创建的setup.exe进程一样,这是一个问题。通常我会调用p1.destroy(),但我在两个类之间建立连接时遇到问题。

任何建议都会非常感谢!

编辑:

private void beginThread() {
        SwingWorker<String, Void>  myWorker = new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() throws Exception {
                //Do some stuff
            }
        return null;
        }
    };
    myWorker.execute();
}

1 个答案:

答案 0 :(得分:2)

假设您在一个单独的线程中运行该进程,您可以从GUI类中调用processThread.interrupt()

然后您只需将try / catch修改为:

try {
    p1.waitFor();
} catch (InterruptedException e) {
    Sys.err(e.toString());
    //don't ignore the exception:
    p1.destroy();
    Thread.currentThread.interrupt(); //reset interrupted flag
}
相关问题