
[历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2013-11-27 标题《Java编程思想》读书笔记Timer TimerTask分类编程 / java / think_in_java 标签java·think in java·TimerTimerTask《Java编程思想》读书笔记Timer TimerTaskTimer和TimerTask详解以下内容根据 The JavaTM Tutorial 和相关API doc翻译整理以供日后参考1.概览2.终止Timer线程3.反复执行一个任务4.进一步分析schedule和scheduleAtFixedRate5.一些注意的问题本章节转自http://blog.csdn.net/ahxu/article/details/249610Timer和TimerTask详解以下内容根据 The JavaTM Tutorial 和相关API doc翻译整理以供日后参考1.概览Timer是一种定时器工具用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。TimerTask一个抽象类它的子类代表一个可以被Timer计划的任务。简单的一个例程importjava.util.Timer;importjava.util.TimerTask;/** * Simple demo that uses java.util.Timer to schedule a task to execute * once 5 seconds have passed. */publicclassReminder{Timertimer;publicReminder(intseconds){timernewTimer();timer.schedule(newRemindTask(),seconds*1000);}classRemindTaskextendsTimerTask{publicvoidrun(){System.out.println(Times up!);timer.cancel();//Terminate the timer thread}}publicstaticvoidmain(Stringargs[]){System.out.println(About to schedule task.);newReminder(5);System.out.println(Task scheduled.);}}运行这个小例子你会首先看到About to schedule task.5秒钟之后你会看到Times up!这个小例子可以说明一些用Timer线程实现和计划执行一个任务的基础步骤实现自定义的TimerTask的子类run方法包含要执行的任务代码在这个例子里这个子类就是RemindTask。实例化Timer类创建计时器后台线程。实例化任务对象 (new RemindTask()).制定执行计划。这里用schedule方法第一个参数是TimerTask对象第二个参数表示开始执行前的延时时间单位是milliseconds这里定义了5000。还有一种方法可以指定任务的执行时间如下例指定任务在11:01 p.m.执行//Get the Date corresponding to 11:01:00 pm today.CalendarcalendarCalendar.getInstance();calendar.set(Calendar.HOUR_OF_DAY,23);calendar.set(Calendar.MINUTE,1);calendar.set(Calendar.SECOND,0);Datetimecalendar.getTime();timernewTimer();timer.schedule(newRemindTask(),time);2.终止Timer线程默认情况下只要一个程序的timer线程在运行那么这个程序就会保持运行。当然你可以通过以下四种方法终止一个timer线程调用timer的cancle方法。你可以从程序的任何地方调用此方法甚至在一个timer task的run方法里。让timer线程成为一个daemon线程可以在创建timer时使用new Timer(true)达到这个目地这样当程序只有daemon线程的时候它就会自动终止运行。当timer相关的所有task执行完毕以后删除所有此timer对象的引用置成null这样timer线程也会终止。调用System.exit方法使整个程序所有线程终止。Reminder的例子使用了第一种方式。在这里不能使用第二种方式因为这里需要程序保持运行直到timer的任务执行完成如果设成daemon那么当main线程结束的时候程序只剩下timer这个daemon线程于是程序不会等timer线程执行task就终止了。有些时候程序的终止与否并不只与timer线程有关。举个例子如果我们使用AWT来beep那么AWT会自动创建一个非daemon线程来保持程序的运行。下面的代码我们对Reminder做了修改加入了beeping功能于是我们需要加入System.exit的调用来终止程序。importjava.util.Timer;importjava.util.TimerTask;importjava.awt.Toolkit;/** * Simple demo that uses java.util.Timer to schedule a task to execute * once 5 seconds have passed. */publicclassReminderBeep{Toolkittoolkit;Timertimer;publicReminderBeep(intseconds){toolkitToolkit.getDefaultToolkit();timernewTimer();timer.schedule(newRemindTask(),seconds*1000);}classRemindTaskextendsTimerTask{publicvoidrun(){System.out.println(Times up!);toolkit.beep();//timer.cancel(); //Not necessary because we call System.exitSystem.exit(0);//Stops the AWT thread (and everything else)}}publicstaticvoidmain(Stringargs[]){System.out.println(About to schedule task.);newReminderBeep(5);System.out.println(Task scheduled.);}}3.反复执行一个任务先看一个例子publicclassAnnoyingBeep{Toolkittoolkit;Timertimer;publicAnnoyingBeep(){toolkitToolkit.getDefaultToolkit();timernewTimer();timer.schedule(newRemindTask(),0,//initial delay1*1000);//subsequent rate}classRemindTaskextendsTimerTask{intnumWarningBeeps3;publicvoidrun(){if(numWarningBeeps0){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 the first beep Beep! //one second after the second beep Times up! //one second after the third beep这里使用了三个参数的schedule方法用来指定task每隔一秒执行一次。如下所列为所有Timer类用来制定计划反复执行task的方法 schedule(TimerTasktask, longdelay, longperiod)schedule(TimerTasktask, Datetime, longperiod)scheduleAtFixedRate(TimerTasktask, longdelay, longperiod)scheduleAtFixedRate(TimerTasktask, DatefirstTime, longperiod)当计划反复执行的任务时如果你注重任务执行的平滑度那么请使用schedule方法如果你在乎的是任务的执行频度那么使用scheduleAtFixedRate方法。 例如这里使用了schedule方法这就意味着所有beep之间的时间间隔至少为1秒也就是说如果有一个beap因为某种原因迟到了未按计划执行那么余下的所有beep都要延时执行。如果我们想让这个程序正好在3秒以后终止无论哪一个beep因为什么原因被延时那么我们需要使用scheduleAtFixedRate方法这样当第一个beep迟到时那么后面的beep就会以最快的速度紧密执行最大限度的压缩间隔时间。4.进一步分析schedule和scheduleAtFixedRate12个参数的schedule在制定任务计划时 如果指定的计划执行时间scheduledExecutionTimesystemCurrentTime则task会被立即执行。scheduledExecutionTime不会因为某一个task的过度执行而改变。23个参数的schedule在制定反复执行一个task的计划时每一次执行这个task的计划执行时间随着前一次的实际执行时间而变也就是scheduledExecutionTime(第n1次)realExecutionTime(第n次)periodTime。也就是说如果第n次执行task时由于某种原因这次执行时间过长执行完后的systemCurrentTimescheduledExecutionTime(第n1次)则此时不做时隔等待立即执行第n1次task而接下来的第n2次task的scheduledExecutionTime(第n2次)就随着变成了realExecutionTime(第n1次)periodTime。说白了这个方法更注重保持间隔时间的稳定。33个参数的scheduleAtFixedRate在制定反复执行一个task的计划时每一次执行这个task的计划执行时间在最初就被定下来了也就是scheduledExecutionTime(第n次)firstExecuteTimen*periodTime如果第n次执行task时由于某种原因这次执行时间过长执行完后的systemCurrentTimescheduledExecutionTime(第n1次)则此时不做period间隔等待立即执行第n1次task而接下来的第n2次的task的scheduledExecutionTime(第n2次)依然还是firstExecuteTimen2)*periodTime这在第一次执行task就定下来了。说白了这个方法更注重保持执行频率的稳定。5.一些注意的问题每一个Timer仅对应唯一一个线程。Timer不保证任务执行的十分精确。Timer类的线程安全的。