为什么我在 ProcessBuilder --Java 中收到 IllegalThreadStateException 错误?

R G*_*ldi 2 java process exit-code processbuilder

此代码导致 IllegalThreadStateException 运行时错误来自 if 语句:

public static void main(String args[]) throws IOException, InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    Process proc = new ProcessBuilder("\"c:\\[directory]/doer.exe\"").start();
    if(proc.exitValue() == 1)
        System.out.println("Output: 1");
}
Run Code Online (Sandbox Code Playgroud)

应该专门运行的可执行文件具有退出代码 1。我做错了什么,我该如何解决?

Luc*_*ens 6

Process#exitValue 的 javadoc 描述了它抛出异常的原因:

https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#exitValue()

抛出: IllegalThreadStateException - 如果此 Process 对象表示的子进程尚未终止

proc.waitFor()在 if 语句之前使用以等待进程完成。