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;
        }

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

  • 相关阅读:
    进程池Pool
    进程间通信-Queue
    多任务版udp聊天器
    列表循环放引用并写出打印结果
    协程实现tcp两个客户端的通讯
    正则匹配身份证和邮箱
    python中上双互斥锁的线程执行流程
    小巧的http live streaming m3u8播放器
    js实现@提到好友
    mongoose多级嵌套操作
  • 原文地址:https://www.cnblogs.com/cxyxiaobao/p/12389059.html
Copyright © 2011-2022 走看看