简体   繁体   English

使用Process.waitFor()和java.lang.InterruptedException的Java多线程

[英]java multithreading using Process.waitFor() and java.lang.InterruptedException

This is the pseudocode of what I have been doing: 这是我一直在做的伪代码:

ProcessBuilder processBuilder = new ProcessBuilder(cmdToExecute);
    Process process = processBuilder.start();
    StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
    StreamGobbler outStreamGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");

    errorGobbler.start();
    outStreamGobbler.start();
    int exitValue = process.waitFor();
    process.destroy();

I am getting InterruptedException while using 我在使用时收到InterruptedException

Process.waitFor() Process.waitFor()

command. 命令。 It was fine when it was a single threaded java app. 当它是单线程Java应用程序时很好。 But now its a multithreaded app, I am getting 但是现在它是一个多线程应用程序,我正在

java.lang.InterruptedException java.lang.InterruptedException

on that particulat line. 在那条特殊线上。 Java doc says: Java文档说:

Throws: InterruptedException - if the current thread is interrupted by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown 抛出:InterruptedException-如果当前线程在等待时被另一个线程中断,则等待结束,并抛出InterruptedException

I understand what it means because 1 thread might be waiting while another wants to wait too but how do I get over this exception and also I will be able to use waitFor(). 我理解这是什么意思,因为1个线程可能正在等待,而另一个线程也想等待,但是我该如何克服此异常,也可以使用waitFor()。

Any help is appreaciated. 任何帮助表示赞赏。 I didn't find necessary to post the code, but let me know if you guys need it. 我发现没有必要发布代码,但是请告知我是否需要。

Code for ExecutorService: ExecutorService的代码:

while(...){
                          .......
        execServ.execute(...);
    }
    execServ.shutdown();
            while(!execServ.isTerminated()){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
                }

I'm not sure you understand what the Javadoc means. 我不确定您了解Javadoc的含义。 It is saying that if some other thread calls interrupt() on the thread that is executing the code you posted before or during its call of waitFor() , an InterruptedException will be thrown. 这是说,如果一些其它线程调用interrupt()正在执行你之前或呼叫期间发布的代码的线程上waitFor()一个InterruptedException将被抛出。 It has nothing to do with two threads waiting for something at the same time. 它与两个线程同时等待某事无关。

Does your program explicitly call interrupt() anywhere? 您的程序是否在任何地方显式调用interrupt() Alternatively, are you executing this process through an ExecutorService ? 或者,您是否通过ExecutorService执行此过程? When you cancel a task that has been submitted to an executor, it may be interrupted. 当您取消已提交给执行者的任务时,该任务可能会被中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM