定时器

    今天来模拟一个定时炸弹的情景,对应于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().getSeconds());

         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().getSeconds());

         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().getSeconds());

         try {

            Thread.sleep(1000);

         } catch (InterruptedExceptione) {

            e.printStackTrace();

         }

      }

   }

}


上面用到了类的循环嵌套调用。


总结:以上的效果可以用于软件系统的定时取邮件,定时统计等功能中。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值