【发布时间】:2017-02-24 18:08:42
【问题描述】:
我正在尝试建立一个交通信号灯系统来控制一个路口。我有一个控制器类,它将执行路口的各个阶段,例如,第一阶段将使用 Thread.sleep 将南北和南北交通信号灯变为绿灯一段时间,然后在第二阶段相同相,但适用于东西向和东西向交通信号灯。
我的问题是我想同时打开每个阶段的所有交通灯,这样南北和南北交通灯会同时变绿和变红。我曾尝试使用 ExecutedService 框架,但它似乎无法正常工作,这是我的代码。如果您需要任何进一步的信息以便给我一个有用的答案,请不要犹豫,问
这是控制器类的启动方法,它将连续运行阶段,控制器将阶段作为对象 LinkedList 的列表。
public void start() throws Exception {
// if there are no phases(cycles) to be executed in sequence
if (phases.isEmpty()) {
throw new Exception("There are no phases been created for the intersection to be controlled");
}
Iterator<Phase> iteratorP = phases.iterator();
//execute phases in sequence
while (iteratorP.hasNext()) {
Phase phase = iteratorP.next();
System.out.println("phase activated: ");
// will activate the phase by turning all the traffic lights in this phase to green light
phase.activate();
}
}
===================================== 这是阶段类。此类将有一个交通灯列表列表,该列表将在一定时间内变为绿色然后变为红色
protected void activate() {
ExecutorService executorService = Executors.newFixedThreadPool(trafficLights.size());
executorService.execute(new Runnable() {
public void run() {
for (TrafficLight tl : trafficLights) {
tl.nextState();
System.out.println("TrafficLight nextState done");
try {
//PrepareToStopSate = Amber Light
//PrepareToGoState = Amber + Red Lights
if (tl.getCurrentState() instanceof PrepareToStopState ||
tl.getCurrentState() instanceof PrepareToGoState) {
System.out.println("wait 2sec");
//will wait for two seconds then chnage the state to next state GoState or StopState
Thread.currentThread().sleep(pause * 1000);
System.out.println("TL nextState done");
tl.nextState();
} else {
//if the state of the traffic light is either GoState(green) or StopState(red)
//wait for (duration) time then change the state
System.out.println("wait duration for green and red");
Thread.currentThread().sleep(duration * 1000);
}
} catch (Exception e) {
}
}
}
});
}
【问题讨论】:
标签: java multithreading traffic