java 处理 IllegalThreadStateException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25979336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:05:05  来源:igfitidea点击:

Handling the IllegalThreadStateException

java

提问by augustus hill

import java.io.*;
class Sysexecute
{
    public static void main(String args[]) throws IOException,InterruptedException,IllegalThreadStateException
    {
        Runtime rt= Runtime.getRuntime();
        Process p=rt.exec("ls");
        System.out.println(p.exitValue());
    }
}

i was learning how to execute system commands in java and this error occured. i tried using throws to negate it but was of no use. please explain the reason and solution

我正在学习如何在 Java 中执行系统命令,但发生了此错误。我尝试使用 throws 来否定它,但没有用。请说明原因和解决方法

actual error:-
Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited
    at java.lang.UNIXProcess.exitValue(UNIXProcess.java:270)
    at Sysexecute.main(Sysexecute.java:8)

回答by Sotirios Delimanolis

Invoke Process#waitFor()before trying to get the exit value. This blocks the current thread until the spawned process terminates. If you don't do this, Process#exitValue()throws

Process#waitFor()在尝试获取退出值之前调用。这会阻塞当前线程,直到产生的进程终止。如果你不这样做,Process#exitValue()抛出

IllegalThreadStateException- if the subprocess represented by this Processobject has not yet terminated

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

回答by Parthiban

Always use waitFor(long timeout,TimeUnit unit) instead of waitFor(), so that the thread will not be blocked indefinitely.

始终使用waitFor(long timeout,TimeUnit unit) 而不是waitFor(),这样线程就不会被无限阻塞。