Semaphore类

Semaphore类是实现aqs机制的典型

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

// 信号量机制
public class SemaphoreDemo {
    public static void main(String[] args) {
        SemaphoreDemo semaphoreTest = new SemaphoreDemo();
        int N = 9;            // 客人数量
        NeteaseSemaphore semaphore = new NeteaseSemaphore(5); // 手牌数量,限制请求数量
        for (int i = 0; i < N; i++) {
            String vipNo = "vip-00" + i;
            new Thread(() -> {
                try {
                    semaphore.acquire(); // 获取令牌

                    semaphoreTest.service(vipNo);

                    semaphore.release(); // 释放令牌
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    // 限流 控制5个线程 同时访问
    public void service(String vipNo) throws InterruptedException {
        System.out.println("楼上出来迎接贵宾一位,贵宾编号" + vipNo + ",...");
        Thread.sleep(new Random().nextInt(3000));
        System.out.println("欢送贵宾出门,贵宾编号" + vipNo);
    }

}

在微服务的限流中hsytrix就是使用了这个方式,但是在分布式环境下,涉及到总数1问题,需要开发者进行解决

Semaphore控制多个线程对资源的抢占:

    public Semaphore(int permits) {
        sync = new NonfairSync(permits);
    }
permits the initial number of permits available.
     *        This value may be negative, in which case releases
     *        must occur before any acquires will be granted.

permits: 总资源数

 

 public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }


public boolean tryAcquire() {
        return sync.nonfairTryAcquireShared(1) >= 0;
    }


 public void release() {
        sync.releaseShared(1);
    }

 public boolean tryAcquire(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        return sync.nonfairTryAcquireShared(permits) >= 0;
    }

提高了如上四个方法进行资源的抢占和释放

 

posted @ 2020-03-01 12:23  菩提树下的韦小宝  阅读(180)  评论(0编辑  收藏  举报