Hello,
I'm learning java on my own and the example in the book to demonstrate threads and synchronization is not working. I'm not able to figure out why the sample will not run. Any ideas?
public enum TrafficLightColor {
RED,
GREEN,
YELLOW;
}
***************>
public class TrafficLightSimulator implements Runnable {
private Thread thrd;
private TrafficLightColor tlc;
boolean stop = false;
boolean changed = false;
TrafficLightSimulator(TrafficLightColor init) {
tlc = init;
thrd = new Thread(this);
thrd.start();
}
public void run() {
while(!stop) {
try {
switch(tlc) {
case GREEN:
Thread.sleep(10000);
break;
case YELLOW:
Thread.sleep(2000);
break;
case RED:
Thread.sleep(12000);
break;
}
} catch(InterruptedException exc) {
System.out.println(exc);
}
changeColor();
}
}
synchronized void changeColor() {
switch(tlc) {
case RED:
tlc = TrafficLightColor.GREEN;
break;
case YELLOW:
tlc = TrafficLightColor.RED;
break;
case GREEN:
tlc = TrafficLightColor.YELLOW;
}
changed = true;
notify();
}
synchronized void waitForChange() {
try {
while(!changed);
wait();
changed = false;
} catch(InterruptedException exc) {
System.out.println(exc);
}
}
synchronized TrafficLightColor getColor() {
return tlc;
}
synchronized void cancel() {
stop = true;
System.out.println("after stop changed. stop = " + stop);
}
}
***************>
public class TrafficLightDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TrafficLightSimulator t1 = new TrafficLightSimulator(TrafficLightColor.GREEN);
for(int i=0; i<9; i++) {
System.out.println(t1.getColor());
t1.waitForChange(); //hanging here?
}
t1.cancel();
}
}