问题描述
我的 Java 程序启动了其他几个 Java 进程。当程序关闭时,所有创建的进程都应该终止。
如果程序通过内部停止命令停止,则可以保存所有数据并关闭进程。我为此使用了关闭挂钩,到目前为止效果很好。
但是如果程序突然终止或用户没有正确关闭,所有进程都会继续运行并且程序在下次启动时无法运行。
如何才能在程序突然停止时执行代码,或者更确切地说,如何停止进程?
启动进程的类:
@Override
public void startProcess() throws IOException {
String command = "java -jar server.jar nogui";
this.process = Runtime.getRuntime().exec(command,null,new CloudFolder(super.getPath()).get());
final InputReader reader = new InputReader();
reader.open();
String in = reader.getinput();
if (in.equals("stop")) {
this.process.destroy();
this.process.getoutputStream().close();
}
}
主类:
public static void main(String[] args) {
// normally the startProcess() Method would be
// called right here.
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// Just to see if it worked
File file = new File("closing");
try {
file.createNewFile();
} catch (IOException exception) {
exception.printstacktrace();
}
}
},"Shutdown-thread"));
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)