package com.heima.test004.enumTest;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 第4题: 定义一个交通灯枚举,包含红灯、绿灯、黄灯,需要有获得下一个灯的方法, 例如:红灯获取下一个灯是绿灯,绿灯获取下一个灯是黄灯。
*
* @author Lee
* 答:
*
*
*/
public class Test003_EnumTest {
public static void main(String[] args) throws Exception {
Lamp currentLamp = Lamp.RED;
new Timer().schedule(new LampController(), 2000);
}
}
//定义一个定时器类
//如果不用这个类,直接在main里边写的话,会使得currentLamp强制定义为final,则无法改变其值
class LampController extends TimerTask {
private Lamp currentLamp;
@Override
public void run() {
currentLamp = currentLamp.turnNext();
System.out.println(currentLamp.getTime());
new Timer().schedule(new LampController(),currentLamp.getTime());
}
}
enum Lamp {
RED(1) {
@Override
public Lamp turnNext() {
System.out.println("现在是红灯");
System.out.println(this.getTime() + "s后变化");
return GREEN;
}
},
GREEN(5) {
@Override
public Lamp turnNext() {
System.out.println("现在是绿灯");
System.out.println(this.getTime() + "s后变化");
return YELLOW;
}
},
YELLOW(3) {
@Override
public Lamp turnNext() {
System.out.println("现在是黄灯");
System.out.println(this.getTime() + "s后变化");
return RED;
}
};
private int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
// 因为每个灯都需要实现变化到下一个的灯的方法(且方法皆不相同),所以将它设为抽象
// 方法体则在每个枚举对象中实现
public abstract Lamp turnNext();
private Lamp() {
}
private Lamp(int time) {
this.time = time;
}
}
未解问题,定时器无法自定义切换时间
最新推荐文章于 2022-12-14 17:50:35 发布