并发编程系列---【Semaphore-同时允许存在几个】

作用:同时允许存在指定的数量,类似组锁

常用场景:1.停车场一共有3个停车位,来了100辆车,这时,一次最多允许停3辆。

     2.系统最大能抗300个并发,只是后就最多设置信号量的值为300,保证服务不崩,能正常用。

复制代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    static class Parking{
        //信号量
        private Semaphore semaphore;

        Parking(int count){
            semaphore = new Semaphore(count);//指定最大同时拥有锁的线程数量
        }

        public void park(){//停车
            try {
                //获取信号量
                semaphore.acquire();//获得锁  =>  相当于 lock方法
                //long time = (long) (Math.random() * 10);//随机时间停车
                System.out.println(Thread.currentThread().getName() + "进入停车场,停车" + 10 + "秒..." );
                Thread.sleep(5000);
                System.out.println(Thread.currentThread().getName() + "开出停车场...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();//释放锁  =>  相当于Unlock方法
            }
        }
    }

    static class Car implements Runnable {
        Parking parking ;

        Car(Parking parking){
            this.parking = parking;
        }

        @Override
        public void run() {
            parking.park();     //进入停车场
        }
    }

    public static void main(String[] args){
        Parking parking = new Parking(3);// 最大允许3个线程持有锁
        int threadnum = 100; //指定创建线程数量
        ExecutorService exec = Executors.newFixedThreadPool(threadnum);
        for(int i = 0 ; i < threadnum ; i++){
           exec.execute(new Car(parking));
        }
        exec.shutdown();
    }
}
复制代码

 

posted on   少年攻城狮  阅读(33)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-12-08 sping源码系列---【2-七大设计原则和23种设计模式】
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示