juc之Semaphore信号量

semaphore称为信号量,用来限制能同时访问共享资源的线程上限,应用场景为共享资源有多个,允许多个线程访问

semaphore示例

        Semaphore semaphore = new Semaphore(3); // 限制上限为3

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        
        ArrayList<Callable<String>> callables = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            int j = i;
            callables.add(()->{
                try {
                    semaphore.acquire(); // 获取信号量
                    Thread.sleep(1000);
                    System.out.println("成功获取semaphore");
                }finally {
                    semaphore.release(); // 执行完毕释放信号量
                    System.out.println("成功释放取semaphore");
                }
                return "1 "+ j;
            });
        }
        List<Future<String>> futures = executorService.invokeAll(callables);

        futures.forEach(stringFuture -> {
            try {
                System.out.println(stringFuture.get());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            }
        });

semaphore应用

  • 使用Semaphore限流,在访问高峰期时,让请求线程阻塞,高峰期过去再释放许可,当然它只适合限制单机线程数量,并且仅是限制线程数,而不是限制资源数(例如连接数,请对比Tomcat LimitLatch的实现)
  • 用Semaphore实现简单连接池,对比『享元模式』下的实现(用wait notify),性能和可读性显然更好,注意下面的实现中线程数和数据库连接数是相等的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值