C/C++教程

并发编程-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);
    }
  • permits表示许可线程的数量
  • fair表示公平性,如果设为true,下次执行的线程会是等待最久的线程

主要方法

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);
    }
  • acquire()表示阻塞并获取许可
  • release()表示释放许可
这篇关于并发编程-AQS之CountDownLatchSemaphore原理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!