Semaphore-停车场

2022-10-16,

模拟20辆车进停车场

停车场容纳总停车量5。
当一辆车进入停车场后,显示牌的剩余车位数响应的减1.
每有一辆车驶出停车场后,显示牌的剩余车位数响应的加1。
停车场剩余车位不足时,车辆只能在外面等待

public class Park {
static Semaphore semaphore=new Semaphore(5); void park(){
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "成功进入停车场");
Thread.sleep(new Random().nextInt(10000));//模拟车辆在停车场停留的时间
System.out.println(Thread.currentThread().getName() + "驶出停车场");
} catch (Exception e) {
e.printStackTrace();
} finally {
semaphore.release();
}
} public static void main(String[] args) {
Park park =new Park();
for (int i = 0; i <20 ; i++) {
new Thread(()->park.park(),i+"号车").start();
}
}
}

Semaphore-停车场的相关教程结束。

《Semaphore-停车场.doc》

下载本文的Word格式文档,以方便收藏与打印。