Semaphore(信号灯)

public class SemaphoreDemo {

    public static void main(String[] args) {

        //三个停车位
        Semaphore sp = new Semaphore(3);


        //停六个汽车
        for (int i = 1; i <=6 ; i++) {
           new Thread(()->{

                   try {
                       sp.acquire();
                       System.out.println(Thread.currentThread().getName()
                               +"\t号车驶入停车位");
                       TimeUnit.SECONDS.sleep(3);
                       System.out.println(Thread.currentThread().getName()
                               +"\t号车驶出停车位");
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   } finally {
                       sp.release();
                   }


           },String.valueOf(i)).start();
        }



    }
}

结果

1    号车驶入停车位
3    号车驶入停车位
2    号车驶入停车位
2    号车驶出停车位
1    号车驶出停车位
3    号车驶出停车位
5    号车驶入停车位
4    号车驶入停车位
6    号车驶入停车位
6    号车驶出停车位
5    号车驶出停车位
4    号车驶出停车位

 

posted @ 2020-03-15 14:07  常温的冰  阅读(97)  评论(0)    收藏  举报