完成Runtime.getRuntime()。exec()方法后杀死Java进程

时间:2016-09-14 12:29:26

标签: java

我使用Runtime.getRuntime().exec()shell环境中执行linux脚本,但我看到java进程在完成此任务后没有被删除。完成此任务后如何停止/终止 java进程。

爪哇

private class Task implements Runnable{

        @Override
        public void run() {
            try {
                        Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
                    }
            } catch (IOException e) {

        };

    }

1 个答案:

答案 0 :(得分:0)

你有几个选择。您可以使用Process#waitFor

阻止任务完成
class Task implements Runnable{
    @Override
    public void run() {
        try {
            final Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
            process.waitFor();
        } catch (final IOException | InterruptedException e) {
            // handle the error
        }
    };
}

如果您认为程序可能会挂起,则可以在waitForThread中将join包裹在超时时间内。超时后,您可以在流程上调用destroy

class Task implements Runnable{
    @Override
    public void run() {
        try {
            final Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
            final Thread thread = new Thread(process::waitFor);
            thread.start();
            thread.join(1000);
            process.destroy();
        } catch (final IOException | InterruptedException e) {
            // handle the error
        }
    };
}
相关问题