Timer的实质上就是一个多线程,从它的类中可以看出:
private TimerThread thread = new TimerThread(queue);
它适用于与时间相关的一些操作,多长时间后运行某个动作,间隔运行某个动作。如:时钟程序我们要每一秒中就刷新一下我们的指针,如,模拟心脏的跳动,Timer都是不错的选择。
public class Time { private final Timer timer = new Timer(true); public void start() { timer.schedule(new TimerTask() { public void run() { System.out.println("Your egg is ready!"); } }, 1000, 1000); } public static void main(String[] args) { Time eggTimer = new Time(); eggTimer.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }
实现了在1秒钟后,每隔一秒钟后运行一次TimerTask。这个Timer设置成的后台线程,在主线程退出后自动退出,一般的我觉得Timer都设置成后台的比较好,前段时间我就发现我写的程序退出了,怎么还有javaw.exe在任务管理器中没有退出啊,还发现我的程序运行了很多次后,在任务管理器中的javaw.exe越来越多,我的机器也就越来越慢了,噢,肯定我的程序,还没有完全推出,结果就找到了一个Timer没有退出,后来我就把我程序的所有的Timer都改后台了。Timer一般都是完成某个任务,如果没有了前台线程,它本来就没有存在的意义了,我程序中是利用的Timer去检测文件的改动,然后通知前台程序文件变了。
public class Time { private final static Timer timer = new Timer(); public void start() { timer.schedule(new TimerTask() { public void run() { System.out.println("Your egg is ready!"); } }, 1000, 1000); } public static void main(String[] args) { Time eggTimer = new Time(); eggTimer.start(); try { Thread.sleep(5000); timer.cancel(); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class Time { private final static Timer timer = new Timer(); public void start() { timer.schedule(new TimerTask() { private int count = 5; public void run() { System.out.println("Your egg is ready!"); if(count--==0) timer.cancel(); } }, 1000, 1000); } public static void main(String[] args) { Time eggTimer = new Time(); eggTimer.start(); } }