/**
* 6辆汽车,停3个停车位
*/
public class SemaphoreDemo {
public static void main(String[] args) {
// 设置许可数量
Semaphore semaphore = new Semaphore(3);
// 模拟6辆车
for (int i = 0; i <=6 ; i++) {
new Thread(()->{
try {
// 抢占
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "抢到了车位");
// 设置随机停车时间
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + "------离开了车位");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}finally {
// 释放
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
JUC Semaphore
最新推荐文章于 2024-05-01 08:36:06 发布