File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TrafficLight {
2
+
3
+ private boolean greenOnRoadA ;
4
+ private ReentrantLock lock ;
5
+
6
+ public TrafficLight () {
7
+ this .greenOnRoadA = true ;
8
+ this .lock = new ReentrantLock ();
9
+ }
10
+
11
+ public void carArrived (
12
+ int carId , // ID of the car
13
+ int roadId , // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
14
+ int direction , // Direction of the car
15
+ Runnable turnGreen , // Use turnGreen.run() to turn light to green on current road
16
+ Runnable crossCar // Use crossCar.run() to make car cross the intersection
17
+ ) {
18
+ this .lock .lock ();
19
+ if (greenOnRoadA && roadId ==2 || !greenOnRoadA && roadId ==1 ){
20
+ greenOnRoadA = !greenOnRoadA ;
21
+ turnGreen .run ();
22
+ }
23
+ crossCar .run ();
24
+ this .lock .unlock ();
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments