Timer 在实际开发中应用场景不多,一般来说都会用其他第三方库来实现。但有时会在一些面试题中出现。
下面我们就针对一道面试题来使用 Timer 定时类。
请模拟写出双重定时器
package com.wjl.test.MyTimer;
import java.sql.Time;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* Timer 在实际开发中应用场景不多,一般来说都会用其他第三方库来实现。但有时会在一些面试题中出现。
* 下面我们就针对一道面试题来使用 Timer 定时类
* 1.请模拟写出双重定时器(面试题)
*/
public class MyTimer {
private static volatile int count = 0;
//内部类
static class TimerTastCus extends TimerTask {
@Override
public void run() {
count = (count + 1) % 2;
System.out.println("count = " + count);
new Timer().schedule(new TimerTastCus(), 2000 + 2000 * count);
}
}
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer();
timer.schedule(new TimerTastCus(), 2000 + 2000 * count);
while (true) {
System.out.println(new Date().getSeconds());
Thread.sleep(1000);
}
}
}