任務 - 在一天中的指定時間打開和關閉燈泡。我需要知道如何根據下面給出的信息來修復我的代碼。我還需要知道我是否正確使用計時器類,也就是說,我的代碼設計是否正確?代碼可能會工作,但它可能是不好的設計,這會在稍後導致問題。我不希望這種情況發生。需要修復我的Java定時器代碼
輸出是(這不是輸出我真的很想:() -
This is the main program
Current time is - xxx
Future time is - xxx+5sec
Future time is - xxx+10sec
Main program ends
Bulb B1 is OFF
所需的輸出 -
This is the main program
Current time is - xxx
Future time is - xxx+5sec
Future time is - xxx+10sec
Bulb B1 is ON //first on
Bulb B1 is OFF //then off
Main program ends//This should always be in the end.
如何解決下面的代碼來獲得我想要的
?Bulb
類
class Bulb {
private boolean state = false;//On or off
private String name;
Bulb(String name){
this.name = name;
}
public void setState(boolean state){
this.state = state;
if(this.state == true){
System.out.println("Bulb " + name + " is ON");
}else{
System.out.println("Bulb " + name + " is OFF");
}
}
public boolean getState(){
return this.state;
}
}
BulbJob
類,這是一TimerTask
import java.util.*;
class BulbJob extends TimerTask{
private Bulb bulbToHandle;
private boolean setBulbStateEqualTo;
BulbJob(Bulb toHandle){
this.bulbToHandle = toHandle;
}
//NOTE: Must be called before run(), otherwise default value is used
public void setBulbStateEqualTo(boolean setBulbStateEqualTo){
this.setBulbStateEqualTo = setBulbStateEqualTo;
}
//NOTE: call run() only before calling above method
public void run(){
this.bulbToHandle.setState(setBulbStateEqualTo);//Set on or off
}
}
BulbScheduler
類 - 此時間表時,燈泡被接通或關斷。
import java.util.*;
@SuppressWarnings("deprecation")
class BulbScheduler {
public static void main(String args[]) throws InterruptedException{
System.out.println("This is the main program");
Timer time = new Timer();
Bulb b1 = new Bulb("B1");
BulbJob bj = new BulbJob(b1);
bj.setBulbStateEqualTo(true);//Task - Turn bulb on at time = afterCurrent
Date current = new Date();//Get current time and execute job ten seconds after this time
Date afterCurrent = (Date) current.clone();
System.out.println("Current time is - " + current);
int currentSecs = current.getSeconds();
int offset = 5;//number of seconds
afterCurrent.setSeconds(currentSecs + offset);
System.out.println("Future time is - " + afterCurrent);
time.schedule(bj, afterCurrent);//Schedule job "bj" at time = afterCurrent
//Now turn the bulb off at new time = newest afterTime
afterCurrent.setSeconds(currentSecs + 2 * offset);
System.out.println("Future time is - " + afterCurrent);
bj.setBulbStateEqualTo(false);//Task - Now turn the bulb off at time = afterCurrent
System.out.println("Main program ends");
}
}
+ 1用於在普通'Thread'的'sleep()'上選擇'TimerTask'。 – asgs 2013-03-11 08:25:37
@asgs - 如何讓「主程序結束」只有在執行完所有內容後纔會出現? – Time 2013-03-11 08:34:39
由於主線程並不依賴於您的工作,恐怕您需要重新設計,以便您可以使用Thread的join()方法等待TimerTask完成。 – asgs 2013-03-11 08:43:07