在 java 中调用超时的外部程序



我遇到了从java调用超时的外部程序的问题。我得到了下面的代码。该程序尝试通过java打开记事本.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);
}
}

您取消了计时器任务killer而不是计时器t
只需与t.cancel()交换killer.cancel();

相关内容

  • 没有找到相关文章

最新更新