Java Reference
In-Depth Information
Whenever the color of the light is needed, its enumeration value is used.
3 . Next, begin defining TrafficLightSimulator , as shown next. TrafficLightSimulator
is the class that encapsulates the traffic light simulation.
Notice that TrafficLightSimulator implements Runnable . This is necessary be-
cause a separate thread is used to run each traffic light. This thread will cycle through
the colors. Two constructors are created. The first lets you specify the initial light
color. The second defaults to red. Both start a new thread to run the light.
Now look at the instance variables. A reference to the traffic light thread is stored in
thrd . The current traffic light color is stored in tlc . The stop variable is used to stop
the simulation. It is initially set to false . The light will run until this variable is set to
true . The changed variable is true when the light has changed.
4 . Next, add the run( ) method, shown here, which begins running the traffic light:
Search WWH ::




Custom Search