java timertask.cancel_Java - Timer.cancel() v/s TimerTask.cancel()

问题

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值