【问题标题】:Why is Java.lang.Process not throwing InterruptedException in this code?为什么 Java.lang.Process 在这段代码中没有抛出 InterruptedException?
【发布时间】:2015-12-18 14:58:37
【问题描述】:

此方法使用 ProcessBuilder 通过我的 Java 应用程序运行外部 C 程序。 我已将其设置为等待 1000 毫秒。 我正在向它传递一个进入无限循环的代码。 但该进程从不抛出interruptedException。

    public void execute(String sourceFileName, long timeout,String inputFile,String outputFile,String errorFile) 
            throws IOException, InterruptedException
    {
        ProcessBuilder builder=new ProcessBuilder(sourceFileName+executableFileExtension);
        Process process=builder.start();
        process.waitFor(timeout,TimeUnit.MILLISECONDS);
    }   

我还注意到该方法返回了控件,但进程继续在后台运行。 为什么会这样?

【问题讨论】:

    标签: java process timeout processbuilder interrupted-exception


    【解决方案1】:

    来自Documentation of Process

    返回: 如果子进程已退出,则为 true;如果在子进程退出之前等待时间已过,则为 false

    所以不要听InterruptedException,你应该检查waitFor()的返回值。

    【讨论】:

      【解决方案2】:

      方法返回控制,但进程继续在后台运行 - 因为您已指定超时限制,到那时,您的 C 程序还没有完成。你自己说它是一个无限循环。

      我正在向它传递一个进入无限循环的代码。但该进程从不抛出interruptedException。

      等待()

      文档说

      抛出: InterruptedException - 如果当前线程在等待时被另一个线程中断,则等待结束并返回 抛出 InterruptedException。

      您当前的线程没有被任何其他线程中断,因此它不会抛出 InterruptedException。

      您的程序的行为似乎没有错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-25
        • 2013-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多