1

当我在 run 方法中调用 cancel() 时,我的 CheckStatus (TimerTask) 没有停止。this.cancel() 也不起作用。我究竟做错了什么?

import java.util.TimerTask;
class CheckStatus extends TimerTask {
   int s = 3;
   public void run() {
      if (s > 0)
      {
         System.out.println("checking status");
         s--;
      }
      else
      {
         System.out.println("cancel");
         cancel();
      }
   }
}

这是我的司机

import java.util.*;
class Game {
   static Timer timer;
   static CheckStatus status;

   public static void main(String[] args) throws InterruptedException {        
      CheckStatus status = new CheckStatus();
      timer = new Timer();
      timer.scheduleAtFixedRate(status, 0, 3000);
   }  
}
4

2 回答 2

2

它对我有用 - 完全使用您发布的代码,我看到:

checking status
checking status
checking status
cancel

...没有别的,表明TimerTask已被取消 - 它再也不会执行了。

Timer当它没有更多工作要做时,您是否期望它自己关闭?它不会自动执行此操作。目前尚不清楚您的更大目标是什么,但避免这种情况的一种选择是TimerTask同时取消Timer- 这将起作用,但它在设计方面并不是非常好,并且意味着TimerTask不能在计时器内很好地运行包含其他任务。

于 2011-12-16T07:21:01.370 回答
2

您正在调用计时器任务的取消方法,但您应该调用计时器本身的取消方法以获得预期的行为。

于 2011-12-16T07:33:54.903 回答