Semaphore,信号量,限流操作

Semaphore

限流操作,限制某个资源同时被访问的次数,基于共享锁实现。 本质上: 抢占一个令牌. -> 如果抢占到令牌,就通行, 否则,就阻塞!

使用场景

  • 停车场

特点

  1. semaphore 也就是我们常说的信号灯,semaphore 可以控制同时访问的线程个数,通过 acquire 获取一个许可,如果没有就等待,通过 release 释放一个许可。

code

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SemaphoreDemo {

    // 20个用户同时访问
    private final static int threadCount = 20;

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

        ExecutorService exec = Executors.newCachedThreadPool();

        // 信号量:限流,同一时刻只允许有permits个线程(用户)同时访问
        int permits = 2;
        final Semaphore semaphore = new Semaphore(permits);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
//                    acquire(semaphore, threadNum);
//                    acquireMore(semaphore, threadNum);
                    tryAcquire(semaphore, threadNum);
//                    tryAcquireWithTime(semaphore, threadNum);
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }
        exec.shutdown();
    }

    /**
     * 获取一个许可
     *
     * @param semaphore
     * @param threadNum
     * @throws Exception
     */
    private static void acquire(Semaphore semaphore, int threadNum) throws Exception {
        // 获取一个许可
        semaphore.acquire();
        log.info("{}", threadNum);
        Thread.sleep(1000);
        // 释放一个许可
        semaphore.release();
    }

    /**
     * 获取多个个许可
     *
     * @param semaphore
     * @param threadNum
     * @throws Exception
     */
    private static void acquireMore(Semaphore semaphore, int threadNum) throws Exception {
        // 获取多个个许可
        semaphore.acquire(2);
        log.info("{}", threadNum);
        Thread.sleep(1000);
        // 释放多个许可
        semaphore.release(2);
    }

    /**
     * 尝试获取一个许可,获取不到则跳过当前包裹的代码
     *
     * @param semaphore
     * @param threadNum
     * @throws Exception
     */
    private static void tryAcquire(Semaphore semaphore, int threadNum) throws Exception {
        // 尝试获取一个许可
        if (semaphore.tryAcquire()) {
            log.info("{}", threadNum);
            Thread.sleep(1000);
            // 释放一个许可
            semaphore.release();
        } else {
            // 获取不到许可
            log.info("获取不到许可:{}", threadNum);
        }
    }

    /**
     * 尝试获取一个许可(带超时时间),给定时间内获取不到则跳过当前包裹的代码
     *
     * @param semaphore
     * @param threadNum
     * @throws Exception
     */
    private static void tryAcquireWithTime(Semaphore semaphore, int threadNum) throws Exception {
        // 尝试获取一个许可(带超时时间)
        if (semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS)) { // 尝试获取一个许可
            log.info("{}", threadNum);
            Thread.sleep(1000);
            // 释放一个许可
            semaphore.release();
        } else {
            // 获取不到许可
            log.info("获取不到许可:{}", threadNum);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljt-tiger

thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值