Java - Timer.cancel() v/s TimerTask.cancel()

我的未来我决定 提交于 2019-11-30 01:55:02

问题


In my Android application, I run a timer and cancel it on some other event:

  class MyTimerTask extends TimerTask {
       override boolean cancel() {
         ...
       }

       override void run() {
         ...
       }
  }

  ...
  Timer t = new Timer();
  t.schedule(new MyTimerTask(),...)
  ...
  t.cancel();

I was expecting t.cancel() to automatically invoke MyTimerTask's cancel() method. But that method is never invoked.

I am wondering what exactly is the different between these two methods and why the second method does not get called automatically.


回答1:


I think you meant to call cancel() on your instance of MyTimerTask

Read the docs for this method...


http://developer.android.com/reference/java/util/TimerTask.html

public boolean cancel ()

Cancels the TimerTask and removes it from the Timer's queue. Generally, it returns false if the call did not prevent a TimerTask from running at least once. Subsequent calls have no effect.


http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#cancel

public void cancel()

Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

Note that calling this method from within the run method of a timer task that was invoked by this timer absolutely guarantees that the ongoing task execution is the last task execution that will ever be performed by this timer.

This method may be called repeatedly; the second and subsequent calls have no effect.


Calling cancel() on the timer stops it and removes all of its queued tasks. But there is no promise to call cancel() on those tasks. Besides, would that make sense given that only 1 of those tasks could be running at any moment?



来源:https://stackoverflow.com/questions/21492693/java-timer-cancel-v-s-timertask-cancel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!