Timer 这个类的作用就是定时启动一个线程来执行任务,一个timer也可以执行多个任务(调用schedule 或 scheduleAtFixedRate)schedule 里面第一个参数是timerTask类的实例,该类实现了Runnable接口。
第二个参数是延迟多少毫秒执行,也可以是一个Date的实例,就是具体某个时间,第三个参数就是可选的,就是每隔多久循环执行一次。scheduleAtFixedRate这个是jdk1.5之后才有的,他对执行频率更加精确,比如我设置了第三个参数是每隔4秒执行一次的,如果有一次它某些原因相隔5才秒执行了,那么再下次就是相隔3秒再执行一次,这样执行频率就比较精确了。
class TimerTest extends TimerTask{
private int i = 0;
public TimerTest(int i){
this.i = i;
}
@Override
public void run() {
i = (i+1) % 2;
System.out.println("bobing~~");
new Timer().schedule(new TimerTest(i),2000+(2000*i));
}
}
new Timer().schedule(new TimerTest(0),2000);
while(true){
System.out.println(new Date().getSeconds());
Thread.sleep(1000);
}
上面这个例子就是演示如何重复执行一个任务,但是每次间隔的时间都不一样,自己控制。