0
我正在做一個書中的例子,它有一個線程示例,其中模擬了交通燈。我瞭解大部分程序,然而,我對這本書所說的「一個單獨的線程將運行每個交通燈」的部分感到困惑,似乎在主應用程序中只創建了一個線程? 我有一個枚舉,列出了我的交通燈的所有常量。Threaded TrafficLightExample許多線程?
public enum TrafficLightColor {
YELLOW,GREEN,RED
}
下面是該程序的其餘部分。
public class TrafficLightSimulator implements Runnable {
private Thread thread;//holds the thread that runs the simulation
private TrafficLightColor color;//holds the traffic light color
boolean stop=false;//set to true to stop the simulation
boolean changed=false;//true when the light has changed
public TrafficLightSimulator(TrafficLightColor inital){
color=inital;
thread=new Thread(this);
thread.start();
}
public TrafficLightSimulator(){
color=TrafficLightColor.RED;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
//start up the light
while(!stop){
try{
switch(color){
case GREEN:
Thread.sleep(10000);//green sleeps for 10 seconds
break;
case RED:
Thread.sleep(2000);//yellow for 2 seconds
break;
case YELLOW:
Thread.sleep(12000);//red for 12 seconds
break;
}
}catch(Exception e){
}
changeColor();
}
}
synchronized void changeColor(){
switch(color){
case RED:
color=TrafficLightColor.GREEN;
break;
case YELLOW:
color=TrafficLightColor.RED;
break;
case GREEN:
color=TrafficLightColor.YELLOW;
}
changed=true;
System.out.println("Notfiy Called We changed the light");
notify();
}
synchronized void waitForChange(){
try{
while(!changed){
System.out.println("waiting for Light to change");
wait();
}
changed=false;
}catch(Exception e){
}
}
synchronized TrafficLightColor getColor(){
return color;
}
synchronized void cancel(){
stop=true;
}
}
class Demo{
public static void main(String[]args){
TrafficLightSimulator t1=new TrafficLightSimulator(TrafficLightColor.YELLOW);
for(int i=0;i<9;i++){
System.out.println(t1.getColor());
t1.waitForChange();
}
t1.cancel();
}
}
有兩個線程,程序的主線程和交通仿真線程,也許這本書有一個錯字,他們的意思*一個單獨的線程運行的每個交通仿真* – Gusman
爲什麼做mehtods需要同步如果他們只有一個在TrafficLightSimulator上運行的線程,那麼是否是hronized? – Eli
或者我猜另一個線程是與TrafficLightSimulator線程通信的主線程? – Eli