经典面试项目--交通灯管理系统(三)

2014-11-24 09:14:43 · 作者: · 浏览: 5
currentLamp = Lamp.S2N;
currentLamp.light();
/*表示首次运行的延迟时间*/
int festTime;
if(currentLamp.getDirection() == Direction.CENTER) {
festTime = 20;
} else {
festTime = 15;
}
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
/*创建一个定时器,如果当前灯所在路线为直行路线则亮20秒绿灯,若是左转路线则为15秒*/
timer.scheduleWithFixedDelay(
new Runnable() {
public void run() {
currentLamp = currentLamp.blackOut();
/*如果当前灯是直行路线上的灯则增加5秒钟绿灯时间*/
if(currentLamp.getDirection() == Direction.CENTER) {
try {
Thread.sleep(5 * 1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
},
festTime, //首次执行延时
15, //执行周期
TimeUnit.SECONDS //指定时间单位为秒
);
}
}
主类(TrafficDemo)运行程序
[java]
class TrafficDemo {
public static void main(String[] args) {
String[] directions = new String[]{
"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"};
// 创建12条路线
for(int i=0;i
new Road(directions[i]);
}
// 交通灯控制器
new LampController();
}
}