0

我正在更新一些旧代码,但不确定复制下面的 Watchdog/TimeoutObserver 功能的最佳方式。但是,这是一种旧的方法,我正在尝试将其更新为更符合 jre7。任何建议或帮助将不胜感激。

import org.pache.tools.ant.util.Watchdog;
import org.pache.tools.ant.util.TimeoutObserver;


 public class executer implemnts TimeoutObserver {

     public String execute() throws Exception {
         Watchdog watchDog = null;

         try { 
                    //instantiate a new watch dog to kill the process
        //if exceeds beyond the time 
        watchDog = new Watchdog(getTimeout());
        watchDog.addTimeoutObserver(this);
        watchDog.start();

                 ... Code to do the execution .....

              } finally {
             if (aWatchDog != null) {
                  aWatchDog.stop();
             }
         } 
         public void timeoutOccured(Watchdog arg0) {
              killedByTimeout = true;

              if (process != null){
                   process.destroy();
              }
              arg0.stop();
        }

      }
4

1 回答 1

0

您可以使用Future.cancel(boolean)方法让任务异步运行一段时间。为了使它工作,你Runnable应该通过使用来检测它的线程中断状态Thread.currentThread().isInterrupted()(这似乎是在你的内部的代码process.destroy())。

下面是Java Concurrency in Practice一书的示例(第 7 章“取消”)。有关此任务的其他一些解决方案,请参阅本书。

public static void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException {
    Future<?> task = taskExec.submit(r);
    try {
        task.get(timeout, unit);
    } catch (TimeoutException e) {
        // task will be cancelled below
    } finally {
        // Harmless if task already completed
        task.cancel(true); // interrupt if running
    }
}
于 2013-03-21T15:21:25.303 回答