本文来自:http://hi.baidu.com/fuqilee/blog/item/2d4c810e04df91ee36d122d4.html
java.util.Timer 是 Sun JDK 提供的一种计时器,用于使后台线程按计划执行指定任务,这些任务可以被执行一次,也可以被定期执行。每个 Timer 对象对应一个后台线程,顺序地执行所有计时器任务。如果完成某个计时器任务的时间太长,那么它会“独占”计时器的任务执行线程,从而可能延迟后续任务的执 行。对 Timer 对象最后的引用完成并且所有未处理的任务都已执行完成后,计时器的任务执行线程会正常终止(并且成为垃圾回收的对象)。以下为一个使用 java.util.Timer 的例子:
import java.util.Timer; import java.util.TimerTask; public class TimerTest { Timer timer; public TimerTest(int seconds) { timer = new Timer(); timer.schedule(new TimerTestTask(), seconds*1000); } class TimerTestTask extends TimerTask { public void run() { system.out.println("In TimerTestTask, execute run method."); timer.cancel(); } } public static void main(String args[]) { system.out.println("Prepare to schedule task."); new TimerTest(2); system.out.println("Task scheduled."); } } |
java.util.Timer 简单易用,比较适合提供轻量级的计时器功能。由于其创建的线程会超出容器的管理范围,因此不能应用于管理的环境中。如果用户需要在 J2EE 环境中提供计时器功能,可考虑使用后面即将介绍的 Commonj Timer 或 WebSphere Application server Scheduler。