我遇到一个问题,从超时调用java的外部程序。我得到了以下代码。此程序尝试通过java打开notepad.exe并在5秒后终止。我面临的问题是虽然它终止了记事本,但java进程仍然保持活动状态(eclipse不会终止)。专家请帮帮忙!
public class ExecTest {
public static void main(String[] args) {
System.out.println("STARTING");
new ExecTest().callNotepad();
System.out.println("ENDING");
}
public ExecTest() {
}
private void callNotepad() {
ProcessBuilder pb = new ProcessBuilder("notepad.exe");
pb.redirectErrorStream(true);
try {
Timer t = new Timer();
pb.redirectErrorStream(true);
Process p = pb.start();
TimerTask killer = new TimeoutProcessKiller(p);
t.schedule(killer, 5000);
try {
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line + "\n");
}
p.waitFor();
System.out.println("HERE!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("Cancelling timer");
killer.cancel();
System.out.println("Cancelled timer");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class TimeoutProcessKiller extends TimerTask {
private Process p;
public TimeoutProcessKiller(Process p) {
this.p = p;
}
@Override
public void run() {
System.out.println("Destroying thread p=" + p);
p.destroy();
System.out.println("Destroyed thread p=" + p);
}
}
答案 0 :(得分:2)
您已取消TimerTask killer
而非计时器t
只需与killer.cancel();
t.cancel()
即可