我使用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) {
};
}
答案 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
}
};
}
如果您认为程序可能会挂起,则可以在waitFor
和Thread
中将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
}
};
}