同步工具类三:计数信号量(java.util.concurrent.Semaphore)

计数信号量用来控制同时访问某个特定资源的操作数或同时执行某个指定操作的数量

A counting semaphore.Conceptually, a semaphore maintains a set of permits. Each acquire blocks if necessary until a permit is available, and then takes it. Each release adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

从概念上来说,Semaphore中维护了一组许可,许可的数量在构造函数中指定。acquire方法将获取一个可用的许可,如果没有可用的许可,该方法会被阻塞,直到Semaphore中有可用的许可。release方法释放一个许可,如果此时存在阻塞中的acqure方法,将释放一个阻塞中的acquire

事实上,Semaphore中只维护可用请求数量,并不包含实际的许可对象

在初始化Semaphore时可以设置其公平性,如果为公平Semaphore,则按照请求时间获得许可,即先发送的请求先获得许可,如果为非公平Semaphore,则先发送的请求未必先获得许可,这有助于提高程序的吞吐量,但是有可能导致某些请求始终获取不到许可(tryAcquire方法不使用公平性设置)

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class Test implements Runnable{
    private static CountDownLatch latch = new CountDownLatch(1);
    private static Semaphore semaphore = new Semaphore(2, true);

    public void run(){
        try {
            latch.await();
            this.work();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void work() throws InterruptedException{
        // 如果等待acquire的线程过多,则终止后续线程的运行
        if(semaphore.getQueueLength() > 2){
            System.out.println("Too many thread waiting to acquire" + Thread.currentThread().getName());
            return;
        }

        semaphore.acquire();
        System.out.println("acquired by " + Thread.currentThread().getName());
        Thread.sleep(1*1000);
        semaphore.release();
    }

    public static void main(String[] args) throws Exception{
        for(int i = 0 ; i < 10 ; i++){
            Thread t = new Thread(new Test());
            t.start();
        }
        //保证所有线程同时运行
        latch.countDown();
    }
}

运行结果如下:

acquired by Thread-9
Too many thread waiting to acquireThread-7
Too many thread waiting to acquireThread-3
Too many thread waiting to acquireThread-5
Too many thread waiting to acquireThread-6
acquired by Thread-1
Too many thread waiting to acquireThread-8
acquired by Thread-2
acquired by Thread-0
acquired by Thread-4

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值