Java认证考试:Java中的Timer和TimerTask的使用
编辑特别推荐:
JAVA中tostring方法的作用
java中substring与substr的用法
Java枚举类型的使用
Timer是一个定时器类,通过该类可以为指定的定时任务进行配置。TimerTask类是一个定时任务类,该类实现了Runnable接口,而且是一个抽象类,如下所示:
public abstract class TimerTask implements Runnable
可以通过继承该类,来实现自己的定时任务。
Timer定时器实例有多种构造方法:
Timer()
创建一个新计时器。
Timer(boolean isDaemon)
创建一个新计时器,可以指定其相关的线程作为守护程序运行。
Timer(String name)
创建一个新计时器,其相关的线程具有指定的名称。
Timer(String name, boolean isDaemon)
创建一个新计时器,其相关的线程具有指定的名称,并且可以指定作为守护程序运行。
下面是一个使用Timer和TimerTask的例子:
package org.shirdrn;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
private int index = 0;
private Timer timer = new Timer();
@Override
public void run() {
System.out.println(index + “。 current time : ” + new Date().getTime());
index++;
}
public void start() {
timer.schedule(this, 5000); // 设置该定时任务MyTimerTask在5s后执行
System.out.println(“scheduled time : ” + this.scheduledExecutionTime()); // 打印出定时任务执行时间
}
public long getScheduleTime() {
return this.scheduledExecutionTime();
}
public static void main(String[] args) {
MyTimerTask mtt = new MyTimerTask();
mtt.start();
}
}
可以得到如下输出:
scheduled time : 1233552478062
0. current time : 1233552478062
这里,只是设置了一个定时任务,只是执行一次。可以调用Timer的scheduleAtFixedRate方法来设置定时任务执行时间,并以指定的速率来重复执行定时任务,修改start方法,如下:
public void start() {
timer.scheduleAtFixedRate(this, new Date(), 2000); // 设置定时任务执行时间,及其速率(2s执行一次)
System.out.println(“scheduled time : ” + this.scheduledExecutionTime());
}
可以得到类似如下的输出:
scheduled time : 1233552825031
0. current time : 1233552825031
1. current time : 1233552827031
2. current time : 1233552829031
3. current time : 1233552831046
4. current time : 1233552833031
5. current time : 1233552835031
6. current time : 1233552837031
7. current time : 1233552839031
8. current time : 1233552841031
可见,使用scheduleAtFixedRate方法设置,可以使run方法体中的代码重复执行,也就是重复执行定时任务,相当于在线程的run方法体中使用一个无穷循环。
另外,Timer类中定义了一个定时任务队列,用来管理基于该定时器Timer的所有定时任务。可以定义多个定时任务,同时指定一个定时器,用同一个定时器来安排定时任务,例如:
package org.shirdrn;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class YourTimerTask extends TimerTask {
private String name; // 定时任务的名称
public YourTimerTask(String name) {
this.name = name;
}
更多免费相关学习经验请访问:Tore_m_1206686_21115_1_1.html”>http://www.shangxueba.com/sTore_m_1206686_21115_1_1.html
那些无法讲述的悲伤和苍凉,