JAVA的心跳包

在应用开发中,经常需要一些周期性的操作,比如每5分钟检查一下新邮件等。对于这样的操作最方便、高效的实现方式就是使用java.util.Timer工具类。比如下面的代码每5分钟检查一遍是否有新邮件:                   private   java.util.Timer   timer;       timer   =   new   Timer(true);       timer.schedule(     new   java.util.TimerTask()   {   public   void   run()   {   //server.checkNewMail();   检查新邮件   }   },   0,   5*60*1000);                           使用这几行代码之后,Timer本身会每隔5分钟调用一遍server.checkNewMail()方法,不需要自己启动线程。Timer本身也是多线程同步的,多个线程可以共用一个Timer,不需要外部的同步代码。       在《The   Java   Tutorial》中有更完整的例子:       public   class   AnnoyingBeep   {   T       Toolkit   toolkit;         Timer   timer;         public   AnnoyingBeep()   {           toolkit   =   Toolkit.getDefaultToolkit();           timer   =   new   Timer();           timer.schedule(new   RemindTask(),   0,   //initial   delay   1*1000);   //subsequent       rate         }                   class   RemindTask   extends   TimerTask   {           int   numWarningBeeps   =   3;           public   void   run()   {             if   (numWarningBeeps   >   0)   {             toolkit.beep();               System.out.println("Beep!");               numWarningBeeps--;             }             else   {               toolkit.beep();               System.out.println("Time&acute;s   up!");               //timer.cancel();   //Not   necessary   because   we   call               System.exit   System.exit(0);               //Stops   the   AWT   thread   (and   everything   else)             }           }         }         ...     }       这段程序,每隔3秒响铃一声,并打印出一行消息。循环3次。程序输出如下:       Task   scheduled.       Beep!       Beep!   //one   second   after   the   first   beep       Beep!   //one   second   after   the   second   beep       Time&acute;s   up!   //one   second   after   the   third   beep                   Timer类也可以方便地用来作为延迟执行,比如下面的代码延迟指定的时间(以秒为单位)执行某操作。类似电视的延迟关机功能。                   ...public   class   ReminderBeep   {         ...   public   ReminderBeep(int   seconds)   {           toolkit   =   Toolkit.getDefaultToolkit();           timer   =   new   Timer();           timer.schedule(new   RemindTask(),   seconds*1000);           }           class   RemindTask   extends   TimerTask   {             public   void   run()   {               System.out.println("Time&acute;s   up!");               toolkit.beep();               //timer.cancel();   //Not   necessary   because   we   call           System.exit   System.exit(0);               //Stops   the   AWT   thread   (and   everything   else)             }           }         ...       }     }       import java.util.concurrent.*;import java.util.*;public class TimerTask implements Runnable ...{    /** *//**定时器事件队列*/    PriorityBlockingQueue<TimerSlot> queue_ =  new PriorityBlockingQueue<TimerSlot>(2048);    /** *//** Creates a new instance of TimerTask */    public TimerTask() ...{    }        /** *//**设置定时器,并放入队列*/    public synchronized Object setTimer(String taskname, String eventname, int timerevent, int delay, Object param)...{        TimerSlot slot = new TimerSlot();        slot.taskname = taskname;        slot.eventname = eventname;        slot.timerevent = timerevent;        slot.expiretime = System.currentTimeMillis() + delay;        slot.param = param;        try ...{            queue_.put(slot);        } catch (Exception ex) ...{        }        return 0;    }        /** *//**去掉指定的定时器*/    protected synchronized int killTimer(Object timer)...{        if (queue_.remove(timer))...{            return 0;        }        return -1;    }        /** *//**关闭操作*/    public void close()...{        queue_.clear();    }        /** *//**线程运行,检查定时器是否触发*/    public void run()...{        while (true)...{            try...{                TimerSlot slot = queue_.peek();                    if (slot == null) ...{                        Thread.sleep(50);                        continue;                    }                    long now = System.currentTimeMillis();                    if (now < slot.expiretime) ...{                        Thread.sleep(Math.min(slot.expiretime-now,50));                        continue;                    }                    queue_.remove();                                        TaskMsg taskmsg = new TaskMsg();                    taskmsg.eventName=slot.eventname;                    taskmsg.eventNo = slot.timerevent;                    taskmsg.msg = (slot.param);                    taskmsg.sender = "__timer";                    taskmsg.receiver = slot.taskname;                    TaskFactory.getInstance().getTaskByName(slot.taskname).                            putmsgtoqueue(taskmsg);            }catch(InterruptedException e)...{                return;            }        }    }        class TimerSlot implements java.lang.Comparable<TimerSlot>...{        public String eventname;        public String taskname;        public int timerevent;        public long expiretime; // ms, System.current+delay        public Object param;        public int compareTo(TimerSlot  other) ...{            return (int)(this.expiretime-other.expiretime);        }    }}  using System;public  class static main ( ){  public int arraySize=10;int a[arraySize]={23,32,12,11,13,35,465,542,16,1};for(int i=0;i<10;i++){  for(int j=0;j<10;j++ )if(a[j]>a[j++])  {  swap(&a[j],&a[j+1]);   }   public swap(int *ar1,int *ar2)  {    int hold=*ar1;      *ar1=*ar2;      *ar2=hold;  }   console.witeline("打印",a[j]);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值