对于定时器,想必生活中用到的不少吧,比如我设置个定时炸弹,又比如我设置的闹钟,都是定时器的实现原理,那么定时器在多线程中怎么实现的呐,是通过这个类 Timer
直接看代码吧,
public class TraditionalTimeTest {
private static int count = 0;
public static void main(String[] args) {
/*new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("BangBang");
}
},10000,1000);*/
class MyTimer extends TimerTask{
@Override
public void run() {
System.out.println("BangBang");
count = (count + 1) % 2;
new Timer().schedule(new MyTimer(),2000);
}
}
new Timer().schedule(new MyTimer(),2000 + 2000*count);
while (true) {
System.out.println(new Date().getSeconds());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}