Skip to content

Commit 5154e4d

Browse files
authored
Create Traffic Light Controlled Intersection.java
1 parent ffee8b8 commit 5154e4d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)