JAVA自带了一个定时器,那就是Timer,要实现一个Timer的demo非常简单:
import java.util.Timer; import java.util.TimerTask; class Task extends TimerTask{ @Override public void run() { System.out.println("******程序执行******"); } } public class TaskTest { public static void main(String[] args){ Timer timer = new Timer(); Task task = new Task() ; timer.schedule(task, 3000); //这里的单位是毫秒 } }
用Eclipse运行一下, 问题来了,明明程序已经执行结束,为何却没有自动关闭呢?
本着学习的精神,百度了一下,发现问这个问题的还真不少。明明已经结束,却为什么没有自动终止程序,这是因为系统默认当Timer运行结束后,如果没有手动终止,那么则只有当系统的垃圾收集被调用的时候才会对其进行回收终止。既然这样,我们可以使用System.gc()来实现程序的手动终止:
import java.util.Timer; import java.util.TimerTask; class Task extends TimerTask{ @Override public void run() { System.out.println("******程序执行******"); System.gc(); } } public class TaskTest { public static void main(String[] args){ Timer timer = new Timer(); Task task = new Task() ; timer.schedule(task, 3000); //这里的单位是毫秒 } }
运行一下,OK,程序运行结束的同时,也成功终止。
但是Sytem.gc()在一个项目中是不能随便调用的,我们做做小测试如此做无可厚非,但是在项目中如此写,太不合实际了。
那么我们可以考虑用Timer类自带的cancel()方法,实现Timer的终止。
来看一下API中对cancel()方法的描述:
public void cancel() Terminates this timer(终结这个timer), discarding any currently scheduled tasks(抛弃所有当前正在执行的TimerTask). 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. 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.
那么我们来实现一下:
import java.util.Timer; import java.util.TimerTask; public class TaskTest { public static void main(String[] args) { Timer timer = new Timer(); // 三秒后开始执行,每隔一秒执行一次 timer.schedule(new Task(timer), 3 * 1000, 1000); } } class Task extends TimerTask { private Timer timer; public Task(Timer timer) { this.timer = timer; } int i = 1; @Override public void run() { System.out.println("******程序执行******"); //当执行到第5秒,程序结束 if (i++ == 5) { this.timer.cancel(); System.out.println("#### 程序结束 ####"); } } }
OK,成功结束程序。