问题
I would like some help understanding and implementing a 'wait until process complete' between the various processes in my application, which need to proceed in a step-wise fashion. My java file runs a batch file which then runs a script. At the conclusion of this there are series of commands that I need to run (through the command line) in a consecutive manner. I'm using:
Runtime.getRuntime().exec("cmd /c start " + command)
to run my batch files and commands (not sure if that information is relevant). Right now what is happening is that the second step that needs to occur in my application is executing before the first step (running the batch file which runs a script) has completed. I need the first step to conclude before running the next series of commands. I really hope I'm making sense!
回答1:
exec() returns an instance of Process, on which you can do waitFor().
Watch out though: I think "start" will actually spawn off a separate Windows process, so waitFor() may return before the command has finished. Try removing "start" from the command line?
回答2:
Easy:
just call the method waitFor() of your Process instance. It will stop the thread until the external process is terminated;
回答3:
Could you put that series of commands into its own batch file?
Otherwise, you could use ProcessBuilder to get a Process object, and call waitFor() on it:
causes the current thread to wait, if necessary, until the process represented by this
Process
object has terminated.
EDIT: Actually, exec() returns a Process
, so you don't need to bother with the ProcessBuilder
part at all.
来源:https://stackoverflow.com/questions/654525/implement-wait-between-processes-in-java