编程语言
首页 > 编程语言> > 并发编程-AQS之CountDownLatchSemaphore原理

并发编程-AQS之CountDownLatchSemaphore原理

作者:互联网

Semaphore

Semaphore是什么

Semaphore是信号量的意思,作用是控制访问特定资源的线程数目,底层依赖AQS的状态State,是在生产当中比较常用的一个工具类。

Semaphore基本用法实例
public class SemaphoreRunner {

    public static void main(String[] args) {
        //初始state = 4,总的容量池
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 10; i++) {
            new Thread(new Task(semaphore, "haxisaite"+i)).start();
        }
    }

    static class Task extends Thread{
        Semaphore semaphore;

        public Task(Semaphore semaphore, String tname) {
            super(tname);
            this.semaphore = semaphore;
        }
        public void run() {
            try {
                //获取公共资源。从容量池里拿出凭据,默认为permits=1个,即state-permits
//                semaphore.acquire();
                if (semaphore.tryAcquire(500, TimeUnit.MILLISECONDS)) {
                    System.out.println(Thread.currentThread().getName() + " :acquire() at time: " + System.currentTimeMillis());
                    Thread.sleep(5000);
                    //释放公共资源。将凭据还回容量池,默认为permits=1个,即state+permits
                    semaphore.release();
                } else {
                    fallBack();
                }
                System.out.println(Thread.currentThread().getName() + " :release() at time: " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public void fallBack() {
            //调用降级方法
            System.out.println("降级!");
        }
    }
}

怎么使用Semaphore

构造方法

Semaphore构造方法
public Semaphore(int permits) {
        sync = new NonfairSync(permits);
    }
public Semaphore(int permits, boolean fair) {
        sync = fair ? new FairSync(permits) : new NonfairSync(permits);
    }

主要方法

Semaphore主要方法
public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
public void acquire(int permits) throws InterruptedException {
        if (permits < 0) throw new IllegalArgumentException();
        sync.acquireSharedInterruptibly(permits);
    }
public void release() {
        sync.releaseShared(1);
    }
public void release(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        sync.releaseShared(permits);
    }

标签:semaphore,AQS,permits,void,编程,CountDownLatchSemaphore,Semaphore,new,public
来源: https://www.cnblogs.com/everyong/p/15421230.html