-2

我认为它应该多次打印消息,但只打印一次?有什么问题?谢谢。

import java.io.IOException;

public class RestartApplication {

    public static void main(String[] args) {       
        System.out.println("Test restarting the application!");       
        restart();
    }

    private static void restart() {
        try{
            Runtime.getRuntime().exec("java RestartApplication");
        }catch(IOException ie){
                   ie.printStackTrace();
        }
    }   
}
4

2 回答 2

2

The reason it only prints once is that you need to print the output from the process, otherwise it will run silently:

Process process = Runtime.getRuntime().exec("java RestartApplication no-run");
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
   System.out.println(line);
}

When the output is displayed you will see a chain of processes each starting a new copy of RestartApplication which will consume a lot resources so you may wish to consider to pass in a command-line argument not to start another process.

Even a simple argument check will save your system by restricting the # of processes to 2:

if (args.length == 0) {
   restart();
}
于 2012-11-03T17:51:12.270 回答
1

我怀疑在命令行上运行它不起作用,所以当你从 Java 运行它时它也不起作用。

System.out.println("Test restarting the application!");
Process exec = Runtime.getRuntime().exec(new String[]{"java", "-cp", System.getProperty("java.class.path"), "RestartApplication"});
BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
for (String line; (line = br.readLine()) != null; )
    System.out.println(line);

印刷

Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
Test restarting the application!
于 2012-11-03T17:46:08.793 回答