这里是引用
package day01;
import java.util.concurrent.Semaphore;
/**
- @author gdz
- @date 21:18 2024/2/17
*/
public class SemaphoreDemo {
public static void main(String[] args) {
//许可的初始数量5
Semaphore semaphore =new Semaphore(3);
//10个线程
for (int i = 0; i <10 ; i++) {
new ParkingLot(semaphore,i).start();
}
}
}
class ParkingLot extends Thread{
private Semaphore semaphore;
private int num;
//构造方法
public ParkingLot(Semaphore semaphore ,int num){
this.semaphore=semaphore;
this.num=num;
}
@Override
public void run() {
try {
//获取许可
semaphore.acquire();
System.out.println(“第”+num+“辆车驶入停车场”);
Thread.sleep(2000);
System.out.println(“第”+num+“辆车驶出-----停车场”);
semaphore.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}