zoukankan      html  css  js  c++  java
  • 多线程之Semaphore登录限流示例

    public static void main(String[] args) {
    
            //允许最大的登录数
            int slots=10;
            ExecutorService executorService = Executors.newFixedThreadPool(slots);
            LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
            //线程池模拟登录
            for (int i = 1; i <= slots; i++) {
                final int num=i;
                executorService.execute(()->{
                     if (loginQueue.tryLogin()){
                         System.out.println("用户:"+num+"登录成功!");
                     }else {
                         System.out.println("用户:"+num+"登录失败!");
                     }
                });
            }
            executorService.shutdown();
    
    
            System.out.println("当前可用许可证数:"+loginQueue.availableSlots());
    
            //此时已经登录了10个用户,再次登录的时候会返回false
            if (loginQueue.tryLogin()){
                System.out.println("登录成功!");
            }else {
                System.out.println("系统登录用户已满,登录失败!");
            }
            //有用户退出登录
            loginQueue.logout();
    
            //再次登录
            if (loginQueue.tryLogin()){
                System.out.println("登录成功!");
            }else {
                System.out.println("系统登录用户已满,登录失败!");
            }
    
        }
    class LoginQueueUsingSemaphore{
    
        private Semaphore semaphore;
    
        /**
         *
         * @param slotLimit
         */
        public LoginQueueUsingSemaphore(int slotLimit){
            semaphore=new Semaphore(slotLimit);
        }
    
        boolean tryLogin() {
            //获取一个凭证
            return semaphore.tryAcquire();
        }
    
        void logout() {
            semaphore.release();
        }
    
        int availableSlots() {
            return semaphore.availablePermits();
        }
    }

    后台兼职接单中,联系我微信:wjf88520

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    UVALive4727:jump
    UVALive
    UVA11795 Mega Man's Mission
    UVA4731:Cellular Network
    UVA11404:Palindromic Subsequence
    设计思路
    阅读计划
    上课未完成代码原因
    《人月神话》读后感
    《软件工程》第十一章总结
  • 原文地址:https://www.cnblogs.com/wujf/p/15541172.html
Copyright © 2011-2022 走看看