用一个布尔型变量保存目前红绿灯状态。
如果目前的车能通过红绿灯,就让他通过。
如果不能,改变灯的状态。
class TrafficLight {
boolean isAGreen;
public TrafficLight() {
isAGreen = true;
}
synchronized 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
) {
if(roadId == 2 && isAGreen==true ||roadId == 1 && isAGreen == false)
{
turnGreen.run();
isAGreen = !isAGreen;
}
crossCar.run();
}
}
当然也可以用信号量的方法,相对速度肯定慢。
class TrafficLight {
private Semaphore s;
boolean isAGreen;
public TrafficLight() {
s = new Semaphore(1);
isAGreen = true;
}
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
) throws InterruptedException {
s.acquire();
if(roadId == 2 && isAGreen==true ||roadId == 1 && isAGreen == false)
{
turnGreen.run();
isAGreen = !isAGreen;
}
crossCar.run();
s.release();
}
}