?? timer.java
字號:
package myoven.timer;
import java.util.*;
public class Timer implements Runnable{
Vector Observers_TimerOn; //預定者計時開始事件的觀察者集合
Vector Observers_TimerOff; //預定者計時結束事件的觀察者集合
Vector Observers_TimerExpired; //預定者計時開始事件的觀察者集合
private int time_remaining;
private static Timer instance;
Thread timeThread;//計時線程
final int TIMEINTERVAL=100;//計時單位
boolean isOn;//標志自身計時狀態 isOn=true;為計時器處于工作狀態
boolean isOk;
//用于判斷外界條件(比如門的閉和與否,可以擴展到其他外界條件)是否允許計時器計時,一旦計時即微波爐處于正常工作狀態.
//比如在此例中用來對門是否關閉,門關閉,將set IsOk=true; or門打開 set IsOk=false;
public static Timer getInstance(){
if(instance==null)
instance=new Timer();
return instance;
}
public Timer() {
Observers_TimerOn=new Vector();
Observers_TimerOff=new Vector();
Observers_TimerExpired=new Vector();
time_remaining=0;
isOn=false;
isOk=true;//在此例中,初始時門處于關閉條件,對于timer來說運行之外部條件成立,所以=true;
}
public int getTime_remaining(){
return time_remaining;
}
public boolean getIsOn(){
return isOn;
}
public boolean getIsOk(){
return isOk;
}
public void setIsOk(boolean isOk){
this.isOk=isOk;
}
/*
public void setIsOn(boolean isOn){
this.isOn=isOn;
}
*/
public void start() {
if (timeThread == null) {
timeThread = new Thread(this);
timeThread.start();
System.out.println("timeThread == null");
}
else
System.out.println("timeThread != null");
}
public void run() {
while (timeThread != null && time_remaining>0 && isOn && isOk) {
time_remaining=time_remaining-1;//時間流逝...
System.out.println(time_remaining);
try {
timeThread.sleep(TIMEINTERVAL);//計時
} catch (InterruptedException e){}
}
if(isOn && isOk){
//isOn==true:說明是超時-計時已滿而不是因為按取消導致烹飪終止
//isOk==true:說明是超時-計時已滿而不是因為外界條件破壞而導致(如此例中開了門)
timeExpired();//超時
timeThread=null;
}
else{//是按取消按鈕而導致烹飪終止
off();//取消按鈕,關閉timer
timeThread=null;
}
}
public void add60secToTime(){
if(isOk){
time_remaining += 60;
}
System.out.println("time_remaining:"+time_remaining);
}
public void setTimeToZero(){
time_remaining=0;
}
public void timeExpired(){//通知所有預定計時超時事件的觀察者
for(int i=0;i<Observers_TimerExpired.size();i++){
((TimerObserver)Observers_TimerExpired.elementAt(i)).recieveTimerNotification();
}
}
public void on(){//通知所有預定計時開始事件的觀察者
isOn=true;
for(int i=0;i<Observers_TimerOn.size();i++){
((TimerObserver)Observers_TimerOn.elementAt(i)).recieveTimerNotification();
}
}
public void off(){//通知所有預定計時結束事件的觀察者
isOn=false;
for(int i=0;i<Observers_TimerOff.size();i++){
((TimerObserver)Observers_TimerOff.elementAt(i)).recieveTimerNotification();
}
}
public void subscribeTimerOn(Object obt){
Observers_TimerOn.add(obt);
}
public void unsubscribeTimerOn(Object obt){
Observers_TimerOn.remove(obt);
}
public void subscribeTimerOff(Object obt){
Observers_TimerOff.add(obt);
}
public void unsubscribeTimerOff(Object obt){
Observers_TimerOff.remove(obt);
}
public void subscribeTimerExpired(Object obt){
Observers_TimerExpired.add(obt);
}
public void unsubscribeTimerExpired(Object obt){
Observers_TimerExpired.remove(obt);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -