未解问题,定时器无法自定义切换时间


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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值