在 java 中调用外部程序超时

Calling external program in java with timeout

我在从 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);
}

}

您取消了 TimerTask killer 而不是 Timer t
只需将 killer.cancel();t.cancel()

交换即可