java并发编程学习juc工具类之Semaphore

1. Semaphore 是什么?

Semaphore 字面意思是信号量的意思,它的作用是控制访问特定资源的线程数目。

2. 怎么使用 Semaphore?

2.1 构造方法

public Semaphore(int permits)
public Semaphore(int permits, boolean fair)

permits 表示许可线程的数量
fair 表示公平性,如果这个设为 true 的话,下次执行的线程会是等待最久的线 程

2.2 重要方法

public void acquire() throws InterruptedException
public void release()
tryAcquire(long timeout, TimeUnit unit)

acquire() 表示阻塞并获取许可
release() 表示释放许可

2.3 基本使用

2.3.1 需求场景

资源访问,服务限流。

2.3.2 代码实现
import java.util.concurrent.Semaphore;

/**
 * @description :可用于流量控制,限制最大的并发访问数
 */
public class SemaphoreSample {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        for (int i=0;i<5;i++){
            new Thread(new Task(semaphore,"silas+"+i)).start();
        }
    }

    static class Task extends Thread{
        Semaphore semaphore;

        public Task(Semaphore semaphore,String tname){
            this.semaphore = semaphore;
            this.setName(tname);
        }

        public void run() {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName()+":acquire() at time:"+System.currentTimeMillis());

                Thread.sleep(2000);

                semaphore.release();
                System.out.println(Thread.currentThread().getName()+":release() at time:"+System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

打印结果:

Thread-1:acquire() at time:1571208530724
Thread-3:acquire() at time:1571208530727
Thread-1:release() at time:1571208532725
Thread-5:acquire() at time:1571208532725
Thread-3:release() at time:1571208532727
Thread-7:acquire() at time:1571208532727
Thread-5:release() at time:1571208534726
Thread-9:acquire() at time:1571208534726
Thread-7:release() at time:1571208534728
Thread-9:release() at time:1571208536727

Process finished with exit code 0

从打印结果可以看出,一次只有两个线程执行 acquire(),只有线程进行 release() 方法后 才会有别的线程执行 acquire()。

相关学习路线

JAVA资深架构师成长路线->架构师筑基必备技能->并发编程进阶

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值