Semaphore-停车场

模拟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();
        }
    }
}
posted @ 2022-07-13 10:04  空中行走的鱼  阅读(68)  评论(0)    收藏  举报