javaruntime.exec

Java : Does Runtime.getRuntime().exec() wait by default?


I have a query regarding Runtime.getRuntime(). I am running the following code.

public class TestMain {
public static void main(String[] args) {
    Runtime rs = Runtime.getRuntime();
    rs.exec("C:\\Windows\\System32\\sampleProgram.exe");
    rs.exec("C:\\Windows\\System32\\sampleProgram2.exe");
    rs.exec("C:\\Windows\\System32\\sampleProgram3.exe");
}
}

Now, if sampleProgram takes more time to execute, will the control wait for the sampleProgram to complete or it will go for sampleProgram2 and will run it parallely ? Please help.


Solution

  • No it does not wait.

    But you can wait for it to finish using the waitFor method.

    rs.exec("C:\\Windows\\System32\\sampleProgram3.exe").waitFor();
    

    Note: If you use a command like cmd start xxxxxx the waitFor method won't really work, because the start command starts the given command/arguments in another process (This is of course a windows specific thing).