首页 > 其他 > 详细

Semaphore(信号灯)

时间:2020-03-15 15:53:39      阅读:105      评论:0      收藏:0      [点我收藏+]
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    号车驶出停车位

 

Semaphore(信号灯)

原文:https://www.cnblogs.com/hpdblogs/p/12497350.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!