信号量-Semaphore控制并发访问数(待完善)

本文介绍Semaphore信号量在并发控制中的作用,特别是在限制资源访问数量的应用场景下,如数据库连接管理和打印机任务调度。通过示例代码展示如何使用Semaphore来实现两个售票窗口的限流,确保同一时间只有一个用户可以购票。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Semaphore限流

在许可可用前会阻塞每一个 acquire(),然后再获取该许可。
每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。
Semaphore 只对可用许可的号码进行计数,并采取相应的行动。拿到信号量的线程可以进入代码,否则就等待。

JDK online doc

http://tool.oschina.net/apidocs/apidoc?api=jdk-zh

应用

  • 数据库访问连接数
  • 打印机

场景描述

用户去两个窗口买票,一个窗口同时只能接收一个用户

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 描述:
 * 信号量
 *
 * @author zhaojianyu
 * @create 2019-01-18 9:13 AM
 */
public class MySemaphore {

    class SemaphoreRunable implements Runnable{

        /**
         *  信号量 和 用户数
         */
        private Semaphore semaphore;
        private int userNum;

        public SemaphoreRunable(Semaphore semaphore, int userNum) {
            this.semaphore = semaphore;
            this.userNum = userNum;
        }

        @Override
        public void run() {
            //获取信号量许可
            try {
                semaphore.acquire();
                System.out.println("用户["+userNum+"]进入窗口,准备买票");
                Thread.sleep((long)(Math.random()*1000));
                System.out.println("用户["+userNum+"]买票完成");
                Thread.sleep((long)(Math.random()*1000));
                System.out.println("用户["+userNum+"]离开售票窗口");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public void execute(){
        //定义窗口个数
        final Semaphore semaphore = new Semaphore(2);
        //使用线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        //模拟20用户
        for (int i = 0; i < 20; i++) {
            threadPool.execute(new SemaphoreRunable(semaphore,i+1));
        }
        threadPool.shutdown();
    }

    public static void main(String[] args){
        MySemaphore mySemaphore = new MySemaphore();
        mySemaphore.execute();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值