版权声明:杨杨杨~~的版权 https://blog.csdn.net/weixin_38316697/article/details/82592802
使用线程写出传统定时器代码
代码:
package xc.Czbk_lx;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
class MyTimerTask extends TimerTask{
private static int count = 0;
public void run() {
//count = (count+1)%2;
System.out.println("第二种定时器(4秒后启动,每4秒走一次)");
new Timer().schedule(new MyTimerTask(),2000+2000*count);
}
}
public class CzbkXc_传统定时器 {
public static void main(String[] args) {
//定时器 第一种
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("第一种定时器(10秒后启动,每2秒走一次)");
}
}, 10000,2000);
//定时器 schedule 调度 第二种
//new Timer().schedule(new MyTimerTask(), 4000);
//这个用来看时间
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
实现效果: