⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 timerbean.java

📁 java模式设计
💻 JAVA
字号:
package TimerBean;import java.awt.*;import java.io.*;import java.util.*;/** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2005</p> * <p>Company: </p> * @author not attributable * @version 1.0 */public class TimerBean  implements Runnable,Serializable {  //定义事件间隔  private int interval = 1000;  //维护事件监听者队列  private Vector timerListeners = new Vector();  //定义一个线程,该线程每睡眠interval指定的时间段后发送一个定制的Timer事件  private Thread runner;  //interval属性的getter方法  public int getInterval() {    return interval;  }  //interval属性的seter方法  public void setInterval(int i) {    interval = i;  }  //一个boolean型属性continue的getter方法,判断线程是否在运行  public boolean isContinue() {    return runner != null;  }  //一个boolean型属性的continue的setter方法,可启动或者停止线程  public void setContinue(boolean b) {    //如果是需要启动线程,那么构造一个线程并启动它        if (b&runner == null)        {          runner = new Thread(this);          runner.start();        } else if (!b&runner != null)        {      //如果是需要中止线程,那么打断它的睡眠,并释放该线程          runner.interrupt();          runner = null;        }  }  //提供一个方法,使得监听者能够注册,加入监听者行列  public synchronized void addTimerListener(TimerListener l) {    timerListeners.addElement(l);  }  //提供一个方法,能够注销注册了的监听者  public synchronized void removeTimerListener(TimerListener l) {    timerListeners.removeElement(l);  }  /* TimerBean作为事件源,向所有监听者列表中的对象发送TimerEvent*/  public void fireTimerEvent(TimerEvent evt) {    //定义一个新队列        Vector currentListeners = null;        //将监听者队列克隆到新对列中        synchronized (this) {          currentListeners = (Vector)timerListeners.clone();        }    //调用克隆出来的监听者队列的每一个监听者的事件处理方法        for (int i = 0; i < currentListeners.size(); i++)        {      		TimerListener listener = (TimerListener)currentListeners.elementAt(i);          	listener.timeElapsed(evt);        }  }  //线程的实际执行过程  public void run () {    if (interval <= 0) return;    boolean isGoing = true;        /* 该线程将睡眠至指定间隔,醒来后发出事件,接着睡眠,醒来,直到被Interrupt打断为止*/    while (isGoing)    {                try                {                        //每睡眠一段时间,就触发一个TimerEvent事件,                        Thread.sleep(interval);                        fireTimerEvent(new TimerEvent(this));                }                //线程的执行被中止掉                catch (InterruptedException e)                {                  isGoing = false;                }    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -