Timer类可以定时执行一些任务,而TimerTask类则表示了定时器执行的任务,它是一个抽象类,实现了Runnable接口。
package org.bupt.test;
import java.util.Timer;
import java.util.TimerTask;
public class Machine extends Thread{
private int a;
private static int count;
public void start(){
super.start();
Timer timer = new Timer(true);//设置一个定时器,并且将其关联的线程设为后台线程。
TimerTask timerTask = new TimerTask(){//设置一个定时器任务的匿名类继承TimerTask类,其中的run 方法表示定时器需要定时完成的任务
public void run() {
while (true) {
reset();
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
timer.schedule(timerTask, 100, 100);//用来设置定时器需要定时执行的任务,第二个参数表示延迟执行时间,即设置后多长时间开始生效,第三个参数表示每次执行任务的间隔时间。
}
private void reset() {
a=0;
}
public void run() {
while (true) {
System.out.println(currentThread().getName()+":"+a++);
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count++==100) {
break;
}
yield();
}
}
public static void main(String[] args) throws InterruptedException {
Machine machine=new Machine();
machine.setName("m1");
machine.start();
}
}
注意:
同一个定时器对象可以执行多个定时任务,间隔时间可以设置为不同。
责任编辑:小草