我正在尝试运行以下Java代码,当我在Windows命令行上通过CTRL + C终止它时,该代码应自动重启:
import java.net.*;
import java.io.*;
public class LineRunner extends Thread {
public static void main(String[] args) throws InterruptedException, IOException{
try {
for (int i = 0; i<10000000; i++) {
Thread.sleep(200);
System.out.print("hithe");
}
}
catch( InterruptedException ioex) {
String[] command = {"C://Program Files//Java//jdk1.7.0_02//bin//java.exe", "LineRunner"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process exec = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
System.out.println("Process exited with " + exec.waitFor());
}
}
}
但是当我从命令行(通过CTRL + C
)终止时,它不会按照我的意愿重启程序。
任何提示表示赞赏,谢谢
答案 0 :(得分:2)
您需要使用addShutdownhook来监听程序退出,然后您可以在那里重新启动程序。
答案 1 :(得分:0)
Ctrl-C将退出JVM,正如评论中已经讨论过的那样。