I am going to simulate a traffic light system.
I created the Road Class which extends JFrame and implements Runnable.
Inside the run() method I added the logic to increase the Y Position of each car and It is now simulating the movements of cars.
But now I need to check the status of the Traffic Light, before move a car.
This is my TrafficLight class,
import java.util.Random;
public class TrafficLight implements Runnable {
volatile boolean stop;
public TrafficLight(boolean stop) {
this.stop = stop;
}
@Override
public void run() {
Random randomGenerator = new Random();
while (true) {
if (stop) {
stop = false; //change current status
} else {
stop = true; //change current status
}
try {
Thread.sleep(2000 + randomGenerator.nextInt(2000));
} catch (Exception ex) {
System.out.println("error");
}
}
}
}
Is there any way to check this volatile variable stop, from my Road Class.
If not please suggest me another solution to do this.
Thanks.
Implement an accessor for stop.
Receive the
TrafficLighton theRoadclass constructor and use it to get access to the stop variable