[英]Make parent thread wait till child thread completes or timeout
我在Unix上運行Java進程。
我需要運行一個由ProcessBuilder主進程派生的外部進程。 主進程等待,直到外部進程完成,然后產生下一個外部進程。 我一直工作到這里。
public static void main(String[] args) { for(...) { int exitVal = runExternalProcess(args); if(exitVal !=0) { failedProcess.add(args); } } }
private int runExternalProcess(String[] args) { ProcessBuilder pb = new ProcessBuilder(args[0], args[1], args[2]); pb.redirectErrorStream(true); Process proc = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader( proc.getInputStream())); String line = null; while ( (line = br.readLine()) != null) LOG.log(Level.SEVERE, line);
//Main thread waits for external process to complete.
//What I need to do is.
// If proc.executionTime() > TIMEOUT
// kill proc;
int exitVal = proc.waitFor();
proc.getInputStream().close();
proc.getOutputStream().close();
proc.getErrorStream().close();
return exitVal;
}
我無法弄清楚的是如何做到這一點。 對於某些輸入,外部進程掛起,在這種情況下,我想等待一個設置的超時時間,如果到那時外部進程還沒有完成,只需殺死它,然后將控制權返回給主進程(以及退出值,以便我可以跟蹤失敗的進程),以便可以啟動下一個外部進程。
我嘗試使用proc.wait(TIMEOUT)然后使用proc.exitValue(); 獲取退出值,但無法使其正常工作。
謝謝!
您可以執行Thread.join(long)或Thread.join(long,int)並在單獨的線程中啟動進程。
添加一些代碼。 (有效,但未在所有極端情況下進行全面測試)
public class Test {
public static void main(String[] args) throws Throwable {
for(int i = 0; i < 3; i++) {
ProcessRunner pr = new ProcessRunner(args);
pr.start();
// wait for 100 ms
pr.join(100);
// process still going on? kill it!
if(!pr.isDone()) {
System.err.println("Destroying process " + pr);
pr.abort();
}
}
}
static class ProcessRunner extends Thread {
ProcessBuilder b;
Process p;
boolean done = false;
ProcessRunner(String[] args) {
super("ProcessRunner " + args); // got lazy here :D
b = new ProcessBuilder(args);
}
public void run() {
try {
p = b.start();
// Do your buffered reader and readline stuff here
// wait for the process to complete
p.waitFor();
}catch(Exception e) {
System.err.println(e.getMessage());
}finally {
// some cleanup code
done = true;
}
}
int exitValue() throws IllegalStateException {
if(p != null) {
return p.exitValue();
}
throw new IllegalStateException("Process not started yet");
}
boolean isDone() {
return done;
}
void abort() {
if(! isDone()) {
// do some cleanup first
p.destroy();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.