题目截图
题目分析
- 用一个trafficController来保证只有一个线程可以改变状态
- 使用semaphore的acquire和realease时候需要try和catch一下异常
- 判断四种可能,直接通行or先改变状态再通行即可
- 状态变量的改变
ac code
class TrafficLight {
// 每个时刻只有一个线程可以来操控红绿灯的变换
// 信号量数 + 公平锁与否
private Semaphore trafficController = new Semaphore(1, true);
private boolean road1CanGo = true;
private boolean road2CanGo = false;
public TrafficLight() {
}
public void carArrived(
int carId, // ID of the car
int roadId, // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
int direction, // Direction of the car
Runnable turnGreen, // Use turnGreen.run() to turn light to green on current road
Runnable crossCar // Use crossCar.run() to make car cross the intersection
) {
// 捕获InterruptedException异常!
try {
// 1.抢占锁
trafficController.acquire();
// 2.判断并改变状态
if ((roadId == 1 && road1CanGo) || (roadId == 2 && road2CanGo)) crossCar.run();
else if (roadId == 1 && !road1CanGo) {
turnGreen.run();
road1CanGo = true;
road2CanGo = false;
crossCar.run();
} else {
turnGreen.run();
road1CanGo = false;
road2CanGo = true;
crossCar.run();
}
// 3.释放锁
trafficController.release();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
总结
- semaphore学习!