Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created May 7, 2018 16:39
Show Gist options
  • Save yukeehan/a1b1fdfbf744ed021c3a4060a552ae4e to your computer and use it in GitHub Desktop.
Save yukeehan/a1b1fdfbf744ed021c3a4060a552ae4e to your computer and use it in GitHub Desktop.
enum TrafficLightColor{
RED, GREEN, YELLOW;
}
class TrafficLightSimulator implements Runnable{
private TrafficLightColor tlc; // holds the traffic light color
private boolean stop = false; // set to true to stop the simulation
private boolean changed = false; // true when the light has changed
TrafficLightSimulator(TrafficLightColor init) {
tlc = init;
}
TrafficLightSimulator() {
tlc = TrafficLightColor.RED;
}
public void run() {
while(!stop) {
try {
switch(tlc) {
case GREEN:
Thread.sleep(10000);
break;
case YELLOW:
Thread.sleep(2000);
break;
case RED:
Thread.sleep(120000);
break;
}
} catch (InterruptedException e) {
// TODO: handle exception
System.out.println(e);
}
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 e) {
System.out.println(e);
}
}
synchronized TrafficLightColor getColor(){
return tlc;
}
synchronized void cancel() {
stop = true;
}
}
public class TrafficLightDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TrafficLightSimulator t1 = new TrafficLightSimulator(TrafficLightColor.GREEN);
Thread thrd = new Thread(t1);
thrd.start();
for(int i=0; i<9; i++) {
System.out.println(t1.getColor());
t1.waitForChange();
}
t1.cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment