Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for process to finish before proceeding in Java

Tags:

java

process

Essentially, I'm making a small program that's going to install some software, and then run some basic commands afterwards to prep that program. However, what is happening is that the program starts its install, and then immediately moves on to the following lines (registration, updates, etc). Of course, that can't happen until it's fully installed, so I'd like to find a way of waiting on the first process before running the second. For example,

    Main.say("Installing...");
    Process p1 = Runtime.getRuntime().exec(dir + "setup.exe /SILENT");
    //Wait here, I need to finish installing first!
    Main.say("Registering...");
    Process p2 = Runtime.getRuntime().exec(installDir + "program.exe /register aaaa-bbbb-cccc");
    Main.say("Updating...");
    Process p4 = Runtime.getRuntime().exec(installDir + "program.exe /update -silent");
like image 400
JTApps Avatar asked Jul 31 '13 13:07

JTApps


People also ask

How do you make a java process wait?

The waitFor() method of Process class is used to wait the currently executing thread until the process executed by the Process object has been completed. The method returns immediately when the subprocess has been terminated and if the subprocess is not terminated, the thread will be blocked.

What is wait () java?

The java. lang. Object. wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).


2 Answers

Call Process#waitFor(). Its Javadoc says:

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Bonus: you get the exit value of the subprocess. So you can check whether it exited successfully with code 0, or whether an error occured (non-zero exit code).

like image 191
mthmulders Avatar answered Oct 02 '22 03:10

mthmulders


you can use Process.waitFor() method

and the doc says

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

like image 36
sanbhat Avatar answered Oct 02 '22 04:10

sanbhat