작업 - 하루 중 특정 시간에 전구를 켜거나 끕니다. 아래 주어진 정보에 따라 코드를 수정하는 방법을 알아야합니다. 타이머 클래스를 정확하게 사용하고 있는지, 즉, 제 코드가 올바른지 알고 싶습니다. 코드가 작동하지만 나중에 문제가 발생할 수있는 잘못된 디자인 일 수 있습니다. 나는 그런 일이 일어나기를 원하지 않는다.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;
}
}
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
클래스입니다
BulbJob
클래스 - 전구를 켜거나 끌 수있다이 일정.
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 일반 스레드의'sleep()'보다 'TimerTask'를 선택하십시오. – asgs
@asgs - 모든 프로그램이 실행 된 후에 만 "주 프로그램 종료"를 수행하려면 어떻게해야합니까? – Time
주 스레드가 당신의 잡에 의존하지 않기 때문에 TimerTask가 완료되기를 기다리기 위해'Thread'의'join()'메소드를 사용할 수 있도록 재 설계해야 할 것 같습니다. – asgs