Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize java code

I have the next code:

Process p = Runtime.getRuntime().exec(args);

and I want my program to wait for the Runtime.getRuntime().exec(args); to finish cause it last 2-3sec and then to continue.

Ideas?

like image 596
Milan Avatar asked Jan 23 '23 08:01

Milan


2 Answers

use Process.waitFor():

Process p = Runtime.getRuntime().exec(args);
int status = p.waitFor();

From JavaDoc:

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 123
sfussenegger Avatar answered Jan 24 '23 22:01

sfussenegger


Here is a sample code:

Process proc = Runtime.getRuntime().exec(ANonJava.exe@);
InputStream in = proc.getInputStream();
byte buff[] = new byte[1024];
int cbRead;

try {
    while ((cbRead = in.read(buff)) != -1) {
        // Use the output of the process...
    }
} catch (IOException e) {
    // Insert code to handle exceptions that occur
    // when reading the process output
}

// No more output was available from the process, so...

// Ensure that the process completes
try {
    proc.waitFor();
} catch (InterruptedException) {
    // Handle exception that could occur when waiting
    // for a spawned process to terminate
}

// Then examine the process exit code
if (proc.exitValue() == 1) {
    // Use the exit value...
}

You can find more on this site: http://docs.rinet.ru/JWP/ch14.htm

like image 38
Andrei Ciobanu Avatar answered Jan 24 '23 21:01

Andrei Ciobanu