模拟一个样例,6辆汽车抢占3个停车位
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
//6个线程抢占3个停车位
public class SemaphoreDemo {
public static void main(String[] args) {
//创建Semaphore,定义许可数量
Semaphore semaphore =new Semaphore(3);
//定义6辆汽车
for(int i=1;i<=6;i++){
new Thread(()->{
try {
//抢占
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到了车位");
//设置停车时间0~1500ms
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1500));
System.out.println(Thread.currentThread().getName()+"----离开了车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
