zoukankan      html  css  js  c++  java
  • java限流(一): Semaphore

    Before obtaining an item each thread must acquire a permit from the semaphore, guaranteeing that an item is available for use.

    When the thread has finished with the item it is returned back to the pool and a permit is returned to the semaphore, allowing

    another thread to acquire that item. Note that no synchronization lock is held when acquire() is called as that would prevent an

    item from being returned to the pool. The semaphore encapsulates the synchronization needed to restrict access to the pool,

    separately from any synchronization needed to maintain the consistency of the pool itself.

    A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual

    exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available,

    or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations),

    that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be

    useful in some specialized contexts, such as deadlock recovery.

    场景:20个人需要买票,但只有2个窗口

    问题:如何控制同一时间并发数为2 ?

    public class SemaphoreDemo {
    
        class SemaphoreRunnable implements Runnable{
    
            private Semaphore semaphore;
            private int user;
    
            public SemaphoreRunnable(Semaphore semaphore, int user) {
                this.semaphore = semaphore;
                this.user = user;
            }
    
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    //不能使用semaphore.tryAcquire();
                    System.out.printf("用户[%s]进入窗口
    ", user );
                    Thread.sleep((long) (Math.random()*10000));
                    System.out.printf("用户[%s]离开窗口
    ", user );
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private void exec(){
            Semaphore semaphore = new Semaphore(2);
            ExecutorService executorService = Executors.newCachedThreadPool();
            for(int i=0; i<20; i++){
                executorService.execute(new SemaphoreRunnable(semaphore, i));
            }
        }
    
        public static void main(String[] args){
            SemaphoreDemo demo = new SemaphoreDemo();
            demo.exec();
        }
    }
  • 相关阅读:
    Keil(MDK) 5 软件安装教程
    JPA 的specification动态查询
    idea 建立JPA项目(二)
    HBase单节点的安装与配置
    【codevs3012+codevs3037】线段覆盖4+线段覆盖5(DP)
    MySQL下载和安装教程
    二、单线程的 JavaScript
    #JS 基础之异步(一)
    JS 基础之: 继承的 六 种实现方式
    源码浅析-Vue3中的13个全局Api
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3980348.html
Copyright © 2011-2022 走看看