学习java多线程的笔记2--Timer类与TimerTask类的使用

今天看了《传智播客_张孝祥_Java多线程与并发库高级应用视频教程》第二讲,只要讲了定时器Timer与TimerTask类的使用

其中有一种使用方案:

见代码:

package cn.yang.thread;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ThreadTimer {

	private static int DELAY=1000;
	private static int PERIOD=2000;
	/**
	 * 定时器的使用
	 * @param args
	 */
	public static void main(String[] args) {
		twoTimer2();
	}
	/**
	 * 重复新建定时器
	 */
	private static void twoTimer2(){
		
		// void schedule(TimerTask task, long delay, long period) 
		//安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。 
		new Timer().schedule(new MyTimerTask(), DELAY);
		while(true){
			System.out.println(new Date().getSeconds());
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){
				
			}
		}
	}
	
	static class   MyTimerTask extends TimerTask{
	
		@Override
		public void run() {
			count=(count+1)%2;
			System.out.println("MyTimerTask-->helloWorld!"+count);
			new Timer().schedule(new MyTimerTask(), 1000+1000*count);
		}
		
	}
	private static int count = 0;
}

上面代码中:

new Timer().schedule(new MyTimerTask(), DELAY);

其中的new MyTimerTask(),MyTimerTask是一个内部类


	static class   MyTimerTask extends TimerTask{
	
		@Override
		public void run() {
			count=(count+1)%2;
			System.out.println("MyTimerTask-->helloWorld!"+count);
			new Timer().schedule(new MyTimerTask(), 1000+1000*count);
		}
		
	}

由于要在main(.)方法中使用MyTimerTask内部类,所以将其声明为 static class MyTimerTask....

在MyTimerTask内部类中的run()方法,有一句:

new Timer().schedule(new MyTimerTask(), 1000+1000*count);
表示新安排一个任务,即
new MyTimerTask()//....
这样就可以实现重复使用定时器了,但要注意MyTimerTask内部类的使用,像下面那样就不行了,会报错: Error:Task already scheduled or cancelled

这样的代码如下:

	private static void twoTimer(){
		// void schedule(TimerTask task, long delay, long period) 
		//安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。 
		new Timer().schedule(new TimerTask() {
			
			@Override
			public void run() {
				System.out.println("helloWorld!");
				//1、再新建一个定时器,不过是使用自身  this,
				//Error:Task already scheduled or cancelled
				//Task已经被使用
				new Timer().schedule(this, DELAY);
			}
		},DELAY,PERIOD);
		
		
		while(true){
			System.out.println(new Date().getSeconds());
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){
				
			}
		}
	}
	

所以,上面是使用定时器Timer类和TimerTask类的一些要注意的问题

每天都要进步才行!加油....

很感谢张老师的java视频教程,可惜他不在世界上了,但还有很多他站起来的!




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值