如何同步java代码

Mil*_*lan 4 java runtime synchronize

我有下一个代码:

Process p = Runtime.getRuntime().exec(args);
Run Code Online (Sandbox Code Playgroud)

我希望我的程序等待Runtime.getRuntime().exec(args); 完成导致它持续2-3秒,然后继续.

想法?

sfu*_*ger 6

使用Process.waitFor():

Process p = Runtime.getRuntime().exec(args);
int status = p.waitFor();
Run Code Online (Sandbox Code Playgroud)

来自JavaDoc:

如果需要,导致当前线程等待,直到此Process对象表示的进程终止.如果子进程已终止,则此方法立即返回.如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出.


And*_*anu 2

这是示例代码:

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...
}
Run Code Online (Sandbox Code Playgroud)

您可以在此网站上找到更多信息:http://docs.rinet.ru/JWP/ch14.htm