import java.util.concurrent.Semaphore;
public class ParkingLotSimulation {
private static final int PARKING_SLOTS = 3;
private static final Semaphore semaphore = new Semaphore(PARKING_SLOTS);
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
new Thread(new Car("Car " + i)).start();
}
}
static class Car implements Runnable {
private final String name;
public Car(String name) {
this.name = name;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(name + " 进入停车场");
Thread.sleep((int) (Math.random() * 2000)); // 模拟停车一段时间
System.out.println(name + " 离开停车场");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
}
- 代码说明:
- 首先定义了一个
PARKING_SLOTS
常量表示停车场的车位数量为3。
- 创建了一个
Semaphore
对象semaphore
,初始许可数量为PARKING_SLOTS
。
- 在
main
方法中,启动了5个线程模拟5辆车。
Car
类实现了Runnable
接口,在run
方法中,首先通过semaphore.acquire()
获取许可,如果没有许可则线程阻塞,直到有许可可用。获取许可后车辆进入停车场,模拟停车一段时间后,通过semaphore.release()
释放许可,确保其他车辆有机会进入停车场。finally
块保证了无论线程执行过程中是否发生异常,许可都会被释放,从而保证了线程安全。