import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreExample {
public static void main(String[] args) {
//限制资源的访问并发数量
Semaphore semaphore = new Semaphore(5);
for (int i = 0; i < 20 ; i ++){
new Car(i,semaphore).start();
}
}
static class Car extends Thread{
private int num;
private Semaphore semaphore;
public Car(int num, Semaphore semaphore){
this.num = num;
this.semaphore = semaphore;
}
@Override
public void run(){
try {
semaphore.acquire(); // 获得令牌
System.out.println("第" + num + "辆车抢到一个车位");
TimeUnit.SECONDS.sleep(100);
System.out.println("第" + num + "辆车 走了 ");
semaphore.release(); // 释放
} catch (InterruptedException e) {
semaphore.release(); // 释放
throw new RuntimeException(e);
}
}
}
}
JUC-Semaphore示例
于 2024-06-25 17:27:27 首次发布