爪哇 - Timer.cancel()V / S TimerTask.cancel() [英] Java - Timer.cancel() v/s TimerTask.cancel()

查看:378
本文介绍了爪哇 - Timer.cancel()V / S TimerTask.cancel()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序,我运行一个计时器,并取消一些其他的事件:

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();

我期待 t.cancel()来自动调用的 MyTimerTask 取消()方法。但该方法是永远不会被调用。

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.

推荐答案

我觉得你的意思是叫取消()您的实例 MyTimerTask

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

公共布​​尔取消()

,它将取消TimerTask和Timer的队列中删除。一般情况下,如果呼叫来自至少运行一次没prevent一个TimerTask返回false。随后的调用没有任何效果。

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 /文档/ API / JAVA / UTIL / Timer.html#取消

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.

请注意,调用从由此计时器调用的计时器任务的run方法中此方法绝对保证正在进行的任务执行是永远不会被此计时器来执行的最后一个任务执行。

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.

调用取消()在定时器停止并删除其所有的排队任务。但没有承诺调用取消()上的任务。此外,会考虑到有意义,只有这些任务1可以在任何时候运行?

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?

这篇关于爪哇 - Timer.cancel()V / S TimerTask.cancel()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆