收藏 分享(赏)

JavaTimer和TimerTask详解.doc

上传人:dzzj200808 文档编号:2230882 上传时间:2018-09-06 格式:DOC 页数:13 大小:44KB
下载 相关 举报
JavaTimer和TimerTask详解.doc_第1页
第1页 / 共13页
JavaTimer和TimerTask详解.doc_第2页
第2页 / 共13页
JavaTimer和TimerTask详解.doc_第3页
第3页 / 共13页
JavaTimer和TimerTask详解.doc_第4页
第4页 / 共13页
JavaTimer和TimerTask详解.doc_第5页
第5页 / 共13页
点击查看更多>>
资源描述

1、JavaTimer 和 TimerTask 详解1.概览Timer 是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。TimerTask 一个抽象类,它的子类代表一个可以被 Timer计划的任务。简单的一个例程:import java.util.Timer;import java.util.TimerTask;/* */* Simple demo that uses java.util.Timer to schedule a task to execute* once 5 seconds have passed.*/public class Remin

2、der .Timer timer;public Reminder(int seconds) .timer = new Timer();timer.schedule(new RemindTask(), seconds*1000);class RemindTask extends TimerTask .public void run() .System.out.println(“Times up!“);timer.cancel(); /Terminate the timer threadpublic static void main(String args) .System.out.println

3、(“About to schedule task.“);new Reminder(5);System.out.println(“Task scheduled.“);运行这个小例子,你会首先看到:About to schedule task.5 秒钟之后你会看到:Times up!这个小例子可以说明一些用 Timer 线程实现和计划执行一个任务的基础步骤:实现自定义的 TimerTask 的子类,run 方法包含要执行的任务代码,在这个例子里,这个子类就是 RemindTask。实例化 Timer 类,创建计时器后台线程。实例化任务对象 (new RemindTask().制定执行计划。这里用

4、schedule 方法,第一个参数是TimerTask 对象,第二个参数表示开始执行前的延时时间(单位是 milliseconds,这里定义了 5000)。还有一种方法可以指定任务的执行时间,如下例,指定任务在 11:01 p.m.执行:/Get the Date corresponding to 11:01:00 pm today.Calendar calendar = Calendar.getInstance();calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 1);calendar.set(Cale

5、ndar.SECOND, 0);Date time = calendar.getTime();timer = new Timer();timer.schedule(new RemindTask(), time);2. 终止 Timer 线程默认情况下,只要一个程序的 timer 线程在运行,那么这个程序就会保持运行。当然,你可以通过以下四种方法终止一个 timer 线程:调用 timer 的 cancle 方法。你可以从程序的任何地方调用此方法,甚至在一个 timer task 的 run 方法里。让 timer 线程成为一个 daemon 线程(可以在创建 timer 时使用 new Tim

6、er(true)达到这个目地),这样当程序只有daemon 线程的时候,它就会自动终止运行。当 timer 相关的所有 task 执行完毕以后,删除所有此 timer对象的引用(置成 null),这样 timer 线程也会终止。调用 System.exit 方法,使整个程序(所有线程)终止。Reminder 的例子使用了第一种方式。在这里不能使用第二种方式,因为这里需要程序保持运行直到 timer 的任务执行完成,如果设成 daemon,那么当 main 线程 结束的时候,程序只剩下 timer 这个 daemon 线程,于是程序不会等 timer 线程执行 task 就终止了。有些时候,程序

7、的终止与否 并不只与 timer 线程有关。举个例子,如果我们使用 AWT 来 beep,那么 AWT 会自动创建一个非 daemon 线程来保持程序的运行。下面的代码我们对 Reminder 做了修改,加入了 beeping 功能,于是我们需要加入System.exit 的调用来终止程序。import java.util.Timer;import java.util.TimerTask;import java.awt.Toolkit;/* */* Simple demo that uses java.util.Timer to schedule a task to execute* once

8、 5 seconds have passed.*/public class ReminderBeep .Toolkit toolkit;Timer timer;public ReminderBeep(int seconds) .toolkit = Toolkit.getDefaultToolkit();timer = new Timer();timer.schedule(new RemindTask(), seconds*1000);class RemindTask extends TimerTask .public void run() .System.out.println(“Times

9、up!“);toolkit.beep();/timer.cancel(); /Not necessary because we call System.exitSystem.exit(0); /Stops the AWT thread (and everything else)public static void main(String args) .System.out.println(“About to schedule task.“);new ReminderBeep(5);System.out.println(“Task scheduled.“);3. 反复执行一个任务先看一个例子:p

10、ublic class AnnoyingBeep .Toolkit toolkit;Timer timer;public AnnoyingBeep() .toolkit = Toolkit.getDefaultToolkit();timer = new Timer();timer.schedule(new RemindTask(),0, /initial delay1*1000); /subsequent rateclass RemindTask extends TimerTask .int numWarningBeeps = 3;public void run() .if (numWarni

11、ngBeeps 0) .toolkit.beep();System.out.println(“Beep!“);numWarningBeeps-; else .toolkit.beep();System.out.println(“Times up!“);/timer.cancel(); /Not necessary because we call System.exitSystem.exit(0); /Stops the AWT thread (and everything else).执行,你会看到如下输出:Task scheduled.Beep!Beep! /one second after

12、 the first beepBeep! /one second after the second beepTimes up! /one second after the third beep这里使用了三个参数的 schedule 方法用来指定 task 每隔一秒执行一次。如下所列为所有 Timer 类用来制定计划反复执行 task 的方法 :schedule(TimerTask task, long delay, long period)schedule(TimerTask task, Date time, long period)scheduleAtFixedRate(TimerTask

13、task, long delay, long period)scheduleAtFixedRate(TimerTask task, Date firstTime, long period)当 计划反复执行的任务时,如果你注重任务执行的平滑度,那么请使用 schedule 方法,如果你在乎的是任务的执行频度那么使用 scheduleAtFixedRate 方法。 例如,这里使用了schedule 方法,这就意味着所有 beep 之间的时间间隔至少为1 秒,也就是说,如 果有一个 beap 因为某种原因迟到了(未按计划执行),那么余下的所有 beep 都要延时执行。如果我们想让这个程序正好在 3

14、秒以后终止,无论哪一个 beep 因为什么原因被延时,那么我们需要使用 scheduleAtFixedRate 方法,这样当第一个 beep 迟到时,那么后面的 beep 就会以最快 的速度紧密执行(最大限度的压缩间隔时间)。4. 进一步分析 schedule 和 scheduleAtFixedRate(1) 2 个参数的 schedule 在制定任务计划时, 如果指定的计划执行时间 scheduledExecutionTime= scheduledExecutionTime(第 n+1 次),则此时不做时隔等待,立即执行第 n+1 次 task,而接下来的第n+2 次 task 的 sche

15、duledExecutionTime(第 n+2 次)就随着变成了 realExecutionTime(第 n+1 次)+periodTime 。说 白了,这个方法更注重保持间隔时间的稳定。(3) 3 个参数的 scheduleAtFixedRate 在制定反复执行一个 task 的计划时,每一次 执行这个 task 的计划执行时间在最初就被定下来了,也就是 scheduledExecutionTime(第 n 次)=firstExecuteTime +n*periodTime;如果第 n 次执行 task 时,由于某种原因这次执行时间过长,执行完后的systemCurrentTime= sc

16、heduledExecutionTime(第 n+1 次),则此时不做 period 间隔等待,立即执行第 n+1 次 task,而接下来的第 n+2 次的 task 的 scheduledExecutionTime(第 n+2 次)依然还是 firstExecuteTime+(n+2)*periodTime 这 在第一次执行 task 就定下来了。说白了,这个方法更注重保持执行频率的稳定。5. 一些注意的问题每一个 Timer 仅对应唯一一个线程。Timer 不保证任务执行的十分精确。Timer 类的线程安全的。考试大温馨提示:本内容来源于网络,仅代表作者个人观点,与本站立场无关,仅供您学习交流使用。其中可能有部分文章经过多次转载而造成文章内容缺失、错误或文章作者不详等问题,请您谅解。如有侵犯您的权利,请联系我们,本站会立即予以处理。

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 大学课件

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报