import java.util.ArrayList;
public class Timer {
private long interval; // 定时器时间,单位 ms
private String expiryAction; // 目标操作
private int timerId; // 定时器Id
private long waitTime; // 定时器等待时间
// 构造函数
public Timer(){
this.waitTime = 0;
}
// 添加定时器
public int StartTimer(long interval, String expiryAction, int id){
this.interval = interval;
this.expiryAction = expiryAction;
this.timerId = id;
return timerId;
}
// 取消定时器
public void StopTimer(int timerId, ArrayList<Timer> timer){
timer.remove(timerId);
}
// 定时器检查
public void PerTickBookkeeping(){
if (this.interval > this.waitTime)
this.waitTime += 10;
else{
System.out.println("定时器"+this.timerId+":"+this.expiryAction);
this.waitTime = 0;
}
}
public long getInterval() {
return interval;
}
public void setInterval(long interval) {
this.interval = interval;
}
public String getExpiryAction() {
return expiryAction;
}
public void setExpiryAction(String expiryAction) {
this.expiryAction = expiryAction;
}
public int getTimerId() {
return timerId;
}
public void setTimerId(int timerId) {
this.timerId = timerId;
}
public long getWaitTime() {
return waitTime;
}
public void setWaitTime(long waitTime) {
this.waitTime = waitTime;
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class DoTimer extends Thread {
private static ArrayList<Timer> timerList;
public static void main(String[] args){
timerList = new ArrayList<Timer>();
Timer timer1 = new Timer();
timer1.StartTimer(3000, "我是第一个定时器,等待3秒", 0);
Timer timer2 = new Timer();
timer2.StartTimer(4000, "我是第二个定时器,等待4秒", 1);
timerList.add(timer1);
timerList.add(timer2);
//public void run(){}
new Thread(){
@Override
public void run() {
while(true){
Iterator<Timer> it = timerList.iterator();
while(it.hasNext()){
it.next().PerTickBookkeeping();
}
try {
sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
timer1.StopTimer(timer1.getTimerId(), timerList);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有