【转载】java Timer TimerTask
  sAAkk3Vxfaa8 2023年11月13日 37 0


1,Timer

Timer的实质上就是一个多线程,从它的类中可以看出:

private TimerThread thread = new TimerThread(queue);

它适用于与时间相关的一些操作,多长时间后运行某个动作,间隔运行某个动作。如:时钟程序我们要每一秒中就刷新一下我们的指针,如,模拟心脏的跳动,Timer都是不错的选择。

 

2,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去检测文件的改动,然后通知前台程序文件变了。

3,Timer运行一段时间,被cancel

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();
		}
	}
}

 

4,Timer运行5次后,被cancel

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();
	}
}

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
sAAkk3Vxfaa8