在Jotm中看到一个很齐全的定时器,贴出来以防备用;
package org.objectweb.jotm;
import java.util.Vector;
/**
*
*对计时器列表中的计时器进行倒计时
*/
class Clock extends Thread {
private TimerManager tmgr;
public Clock(TimerManager tmgr) {
super("JotmClock");
if (TraceTm.jta.isDebugEnabled()) {
TraceTm.jta.debug("Clock constructor");
}
this.tmgr = tmgr;
}
public void run() {
tmgr.clock();
}
}
/**
*
*青年人网站提示:出去计时器列表中的过期计时器,如倒计时为负数
*/
class Batch extends Thread {
private TimerManager tmgr;
public Batch(TimerManager tmgr) {
super("JotmBatch");
if (TraceTm.jta.isDebugEnabled()) {
TraceTm.jta.debug("Batch constructor");
}
this.tmgr = tmgr;
}
public void run() {
tmgr.batch();
}
}
/**
*含有两个计时器列表,并且含有两个线程,一个线程进行计时器的倒计时,
*一个线程移除过期计时器并且执行计时器的监听器动作;
*/
public class TimerManager {
// threads managing the service.
private static Batch batchThread;
private static Clock clockThread;
// lists
//计时器列表
private Vector timerList = new Vector();
//过期计时器列表
private Vector expiredList = new Vector();
//单例
private static TimerManager unique = null;
private static boolean shuttingdown = false;
/**
* Constructor
*/
private TimerManager() {
// launch threads for timers
batchThread = new Batch(this);
batchThread.setDaemon(true);
batchThread.start();
clockThread = new Clock(this);
clockThread.setDaemon(true);
clockThread.start();
}
/**
* 这个时间管理器是一个单例类;
*/
public static TimerManager getInstance() {
if (unique == null)
unique = new TimerManager();
return unique;
}
//停止时间管理器中的计时器;
public static void stop(boolean force) {
if (TraceTm.jta.isDebugEnabled()) {
TraceTm.jta.debug("Stop TimerManager");
}
TimerManager tmgr = getInstance();
shuttingdown = true;
while (clockThread.isAlive() || batchThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
}
if (TraceTm.jta.isDebugEnabled()) {
TraceTm.jta.debug("TimerManager has stopped");
}
}
public static void stop() {
stop(true);
}
/**
* cney speed up the clock x1000 when shutting down
* update all timers in the list
* each timer expired is put in a special list of expired timers
* they will be processed then by the Batch Thread.
*/
责任编辑:小草