当执行的进程需要很长时间才能执行时,如何从getRuntime.exec()中出来?

时间:2014-03-12 17:10:47

标签: java command-line process

在Java程序内部我运行以下命令?

Process p = Runtime.getRuntime().exec("java -cp - src\ MyCode");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream));

程序MyCode是一个java程序。

现在,MyCode可以进入infinite looplong execution cycle等情况。目前,在这种情况下,进程p正在等待MyCode'永远'。我需要的是,每当MyCode执行超过一定时间时,我希望进程p结束或被销毁,以便我可以继续主程序中的下一行。

感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

Apache commons exec包含一个ExecuteWatchdog类https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/ExecuteWatchdog.html

ExecuteWatchdog watchdog = new ExecuteWatchdog(30000);
Executer exec = new Executer(myloghandler, watchdog);
exec.setCommandLine(mycmdline);
int exitvalue = exec.execute();
if (Execute.isFailure(exitvalue) && watchdog.killedProcess()) {
    // it was killed on purpose by the watchdog
}

答案 1 :(得分:0)

我建议您使用ScheduledExecutorService

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

然后您可以定义Stop Process类:

class StopProcess implements Runnable {
    @Override
    public void run() {
        // do some needed work
    }
} 

然后你可以这样做:

scheduler.schedule(new StopProcess(), 5, TimeUnit.SECONDS);