Java Multithreading Example

Step 1

Implement a traffic light object with a turnGreen(int roadNumber) method. When a car is at the intersection, the road the car is on will call this method and pass its number. A call to the turnGreen method can be viewed as a request for the traffic light to turn green so a waiting car can proceed through the intersection. For example, if a car on road 1 is waiting at the intersection, road number 1 calls the turnGreen method, and the method should print out:

Light turned green by road 1
Waiting for road 1 car to clear intersection
10 9 8 7 6 5 4 3 2 1 0
Use a loop to print a countdown of the waiting period from 10 to 0. During each iteration of the loop, request that the Thread sleep for at least 10 milliseconds. This delay represents the time that it takes for a car to proceed through the intersection.

Step 2

A road is a simple queue. The first car in the road will call turnGreen and be removed. After waiting a short amount of time (for example, 250 milliseconds), the next car in the road will call turnGreen, until the road is empty.

Implement a RoadRunnable class. Part of the class code has been provided for you: