zoukankan      html  css  js  c++  java
  • 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;
        }

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

  • 相关阅读:
    剩余类&完全剩余组
    同余验算法
    一种快速余数求法
    同余的性质II
    同余初步
    求N个数的最小公倍数
    N个数GCD求解法
    快速求解GCD的三个Trick
    质数的几个有趣问题
    等比数列求和公式
  • 原文地址:https://www.cnblogs.com/cxyxiaobao/p/12389059.html
Copyright © 2011-2022 走看看