今天来模拟一个定时炸弹的情景,对应于JDK中的类,使用java.util.Timer来做定时非常适合这个情况。
首先来实现一个简单应用:
publicstaticvoid main(String[]args){ new Timer().schedule(new TimerTask(){ publicvoid run(){ System.out.println("explode"); } },2000);
while(true){ System.out.println(newDate(). try { Thread.sleep(1000); } catch (InterruptedExceptione) { e.printStackTrace(); } } } |
实现效果:
从上面可以看到一次爆炸效果后不再出现了,也就是每次都要实例化一个TimerTask。
增加需求:如果爆炸效果不断实现,只是第一次来的比较慢,以后爆炸的频率快一些,怎么做?
publicstaticvoid main(String[]args){ new Timer().schedule(new TimerTask(){ publicvoid run(){ System.out.println("explode"); } },2000,1000);
while(true){ System.out.println(new Date(). try { Thread.sleep(1000); } catch (InterruptedExceptione) { e.printStackTrace(); } } } |
效果如下:
以上实现的效果仍然不是很灵活,如果想做成第一次2秒爆炸一次,第二次4秒爆炸一次,第三次2秒,第四次4秒……怎么办?
publicclass test1 { privatestaticintcount=0; publicstaticvoid main(String[]args){ class MyTimerTaskextends TimerTask{ publicvoidrun(){ System.out.println("explode"); count=(count+1)%2; new Timer().schedule(new MyTimerTask(),2000+count*2000); } }
new Timer().schedule(new MyTimerTask(),2000);
while(true){ System.out.println(new Date(). try { Thread.sleep(1000); } catch (InterruptedExceptione) { e.printStackTrace(); } } } } |
上面用到了类的循环嵌套调用。
总结:以上的效果可以用于软件系统的定时取邮件,定时统计等功能中。