Java并发编程——AQS组件之信号量(Semaphore)

本文介绍了Java并发编程中的AQS组件——信号量Semaphore。Semaphore用于限制并发访问线程的数量,常用于数据库连接等有限资源的访问控制。文章详细讲解了Semaphore的用法,包括单一许可、多个许可及超过线程数丢弃场景,并提供了相关代码示例。

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

一、AQS组件——信号量Semaphore

1. 信号量(Semaphore)介绍:

  • 作用:用于保证同一时间并发访问线程的数目。
  • 信号量在操作系统中是很重要的概念,Java并发库里的Semaphore就可以很轻松的完成类似操作系统信号量的控制;
  • Semaphore使用acquire方法和release方法来实现控制;
  • 在数据结构中我们学过链表,链表正常是可以保存无限个节点的,而Semaphore可以实现有限大小的列表。

2.使用场景

 仅能提供有限访问的资源。比如数据库连接。

二、信号量(Semaphore)的使用

1.允许单一许可场景

期望:有20个线程,每次只允许3个线程同时执行test()方法,具体代码如下:

@Slf4j
public class SemaphorehExample1 {
   

    private static final int threadCount = 200;

    public static void main(String[] args) throws InterruptedException {
   

        ExecutorService executorService = Executors.newCachedThreadPool();

        //实例化Semaphore,并设置允许的并发数
        final Semaphore semaphore = new Semaphore(3);

        for (int i=0; i<threadCount; i++){
   
            final int threadNum = i;
            executorService.execute(()->{
   
                try {
   
                    semaphore.acquire(); //拿到一个许可,执行后面的test()语句
                    test(threadNum);
                    semaphore.release();//释放一个许可
                }catch (Exception e){
   
                    log.error("exception",e);
                }finally {
   
                }
            });
        }
        executorService.shutdown();
    }

    private static void test(int threadNum) throws InterruptedException {
   
        log.info("{}",threadNum);
        Thread.sleep(1000);
    }
}

执行结果部分内容如下:

...
23:06:41.896 [pool-1-thread-2] INFO com.mmall.concurrency.example.aqs.SemaphorehExample1 - 1
23:06:41.896 [pool-1-thread-1] INFO com.mmall.concurrency.example.aqs.SemaphorehExample1 - 0
23:06:41.903 [pool-1-thread-3</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值