Timer定时器的 schedule()方法

timer.schedule(new MyTask(),long time1,long timer2);

今天算是彻底的搞懂了这个曾经让我为之头疼的方法。下面我就重点介绍一下:

第一个参数,是 TimerTask 类,在包:import java.util.TimerTask .使用者要继承该类,并实现public void run() 方法,因为 TimerTask 类 实现了 Runnable 接口。

第二个参数的意思是,当你调用该方法后,该方法必然会调用 TimerTask 类 TimerTask 类 中的 run()方法,这个参数就是这两者之间的差值,转换成汉语的意思就是说,用户调用 schedule() 方法后,要等待这么长的时间才可以第一次执行run() 方法。

第三个参数的意思就是,第一次调用之后,从第二次开始每隔多长的时间调用一次 run() 方法。

[附:]

     仔细研读java api,发现:

  schedule(TimerTask task, long delay)的注释:Schedules thespecified task for execution after the specifieddelay。大意是在延时delay毫秒后执行task。并没有提到重复执行

  schedule(TimerTask task, long delay, long period)的注释:Schedulesthe specified task for repeated fixed-delay execution, beginningafter the specified delay。大意是在延时delay毫秒后重复的执行task,周期是period毫秒。

  这样问题就很明确

       schedule(TimerTask task, longdelay)只执行一次

      schedule(TimerTask task, long delay, longperiod)才是重复的执行

      关键的问题在于我们都误以为schedule就是重复的执行,而没有仔细的研究API,一方面也是英文能力不够,浏览API的过程中不能很快的理解到含义。

猜你喜欢

转载自blog.csdn.net/fengyeNom1/article/details/85694445