// 基本用法示例 semaphore.acquire(); try {
// 访问共享资源
doSomething();
} finally {
semaphore.release();
}
public class ParkingLot {
private Semaphore parkingSpots = new Semaphore(3);
public void parkCar(String carId) {
try {
parkingSpots.acquire();
System.out.println(carId + " 成功停入车位");
// 模拟停车时间
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
System.out.println(carId + " 离开车位");
parkingSpots.release();
}
}
}
你可能想看: