Java timer.cancel()未停止计时器



我是Java的新手,在输入正确的命令后,我一直在尝试使用Java.util.timer来重置现有的计时器。

但是,我无法正确地取消timertask,因此如果多次调用该方法,则计时器线程会运行timertsk的多个实例。如有任何帮助,我们将不胜感激。

编辑:我已经更改了新Timer()的位置,但它似乎并没有修复它。

Timer timer = new Timer();
TimerTask ttimer = new TimerTask() {
    public void run() {
    System.out.println("ping");
    }   
};
public static void main (String[] args) {
    Timer timer = new Timer();
    while (true) {
      //BufferedReader to read input
      //Something
      if (input[0].equals("r")) {
         time t = new time();
         time.RestartTimer();
      }
    }
}
public void RestartTimer() {
        ttimer.cancel();
        timer.cancel();
        Timer timer = new Timer();
        TimerTask ttimer = new TimerTask() {
            public void run() {
            System.out.println("ping");
            }   
        };
        timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}    

之所以发生这种情况,是因为您正在创建一个新的时间类实例(时间t=new time();)while循环内部。相反:

 public static void main (String[] args) {
   time t = new time();  // create an instance of time class
   while (true) {
      //Something
      if (input[0].equals("r")) {
         // call RestartTimer on the same in
         t.RestartTimer();
      }
    }
 }

同样在RestartTimer()函数中,您正在创建Timer的新实例。更改如下:

public void RestartTimer() {
    ttimer.cancel();
    timer.cancel();
    timer = new Timer();
    TimerTask ttimer = new TimerTask() {
        public void run() {
        System.out.println("ping");
        }   
    };
    timer.scheduleAtFixedRate(ttimer, 10000, 10000);
}  

time.RestartTimer();除非您更改方法的修饰符,或者通过在main方法中使用静态对象来调用此方法,否则语句将不会被调用。我认为这是你的计时器没有得到更新的唯一原因。

相关内容

最新更新