用synchronized实现Semaphore

介绍

基于Semaphore的功能,主要用来实现并发和限流,本文采用synchronized来实现Semaphore基础功能。关于Semaphore的说明,请参考JDK1.8 信号量(Semaphore)的基本使用

代码实现

public class MySemaphore {

    private volatile int count;
    private volatile int waitCount = 0;

    /**
     * 初始化信号量
     * @param count
     */
    public MySemaphore(int count) {
        this.count = count;
    }

    /**
     * 获取信号量
     * @throws InterruptedException
     */
    public void acquire() throws InterruptedException {
        while (true) {
            //大量线程在此处等锁
            //执行wait的线程被唤醒后, 重新加入抢锁操作
            waitCount++;
            synchronized (this) {
                if (this.count > 0) {
                    this.count--;
                    waitCount--;
                    break;
                }
                this.wait();
            }
            waitCount--;
            //退出synchronized代码块,释放锁
        }
    }

    /**
     * 释放锁,通知所有等待线程进行抢锁
     */
    public void release() {
        synchronized (this) {
            this.count++;
            this.notifyAll();
        }
    }

    /**
     * 可用的信号量
     * @return
     */
    public int availablePermits(){
        return this.count;
    }

    /**
     * 阻塞线程的个数
     * @return
     */
    public int getQueueLength(){
        return waitCount;
    }
}

上述代码主要实现了acquire(),release(),availablePermits()和getQueueLength()最基础的功能。

测试代码

package sample;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {



    public static void main(String[] args) {

//        Semaphore semaphore=new Semaphore(24);
        MySemaphore semaphore = new MySemaphore(24);

//        int count = semaphore.availablePermits();
//        System.out.println("可用信号量 count1: " + count);
//        //增加20个信号量
//        semaphore.release(20);
        int count = semaphore.availablePermits();
        //此时信号量个数为24个, 可以支持同时跑24个线程
        System.out.println("可用信号量 count2: " + count);
        for (int i = 0; i < 200; i ++){
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("" + Thread.currentThread().getName() + " 进入" + " 时间: " + System.currentTimeMillis());
                    Thread.sleep(200);
                    System.out.println("" + Thread.currentThread().getName() + " 退出" + " 时间: " + System.currentTimeMillis());
                    semap
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值