在Java程序内部我运行以下命令?
Process p = Runtime.getRuntime().exec("java -cp - src\ MyCode");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream));
程序MyCode是一个java程序。
现在,MyCode可以进入infinite loop
或long execution cycle
等情况。目前,在这种情况下,进程p正在等待MyCode'永远'。我需要的是,每当MyCode执行超过一定时间时,我希望进程p结束或被销毁,以便我可以继续主程序中的下一行。
感谢任何帮助!
答案 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);