Java并发编程-Semaphore使用

本文通过实例演示了如何使用Java中的Semaphore类来控制并发线程的数量,确保在资源有限的情况下,只有设定数量的线程可以同时执行。示例中设置了30个线程和10个许可,展示了一次只允许10个线程执行的效果。

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

Java并发编程-Semaphore使用
使用场景:Semaphore(信号量)同时运行多少个并发执行,比如我现在设置30个线程访问,可以通过Semaphore控制同时多个线程同时访问的,

代码如下:

public class SemaphoreTest {
    private static final int THREAD_COUNT = 30;
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);//设置30个线程
    private static Semaphore semaphore = new Semaphore(10);//并发控制10个

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println(Thread.currentThread().getName()+"---------");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}

pool-1-thread-1---------
pool-1-thread-2---------
pool-1-thread-3---------
pool-1-thread-4---------
pool-1-thread-5---------
pool-1-thread-6---------
pool-1-thread-7---------
pool-1-thread-9---------
pool-1-thread-8---------
pool-1-thread-10---------
pool-1-thread-13---------
pool-1-thread-12---------
pool-1-thread-11---------
pool-1-thread-14---------
pool-1-thread-17---------
pool-1-thread-16---------
pool-1-thread-15---------
pool-1-thread-20---------
pool-1-thread-19---------
pool-1-thread-18---------
pool-1-thread-21---------
pool-1-thread-22---------
pool-1-thread-23---------
pool-1-thread-24---------
pool-1-thread-25---------
pool-1-thread-26---------
pool-1-thread-27---------
pool-1-thread-29---------
pool-1-thread-28---------
pool-1-thread-30---------
运行结果分析:可以看到输出时,一次输出10个,一共输出3次。也就是每次只允许10个线程进入执行任务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值