Appearance
10_Semaphore.md
Semaphore 是一个计数信号量,用于控制同时访问特定资源的线程数量。它通过协调各个线程,以保证合理的使用资源。
一个使用Semaphore来控制停车场的示例
java
package io.alex.concurrent;
import java.util.concurrent.Semaphore;
public class ParkingSemaphoreExample {
// 停车场同时容纳的车辆数
private int count = 100;
// 停车场
private Semaphore semaphore = new Semaphore(count);
public void park() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "进入停车场,剩余车位:" + semaphore.availablePermits());
Thread.sleep(new java.util.Random().nextInt(24000));
System.out.println(Thread.currentThread().getName() + "离开停车场,剩余车位:" + semaphore.availablePermits());
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
ParkingSemaphoreExample parking = new ParkingSemaphoreExample();
for (int i = 0; i < 200; i++) {
Thread.sleep(100);
new Thread(() -> parking.park()).start();
}
}
}