zoukankan      html  css  js  c++  java
  • JDK文档中关于Semaphore的正确使用以及使用场景

    import java.util.concurrent.Semaphore;
    
    /**
     * 
     * JDK文档使用备注:<br>
     * Semaphores are often used to restrict the number of threads than
     * can access some (physical or logical) resource. For example, here is a class
     * that uses a semaphore to control access to a pool of items:
     *
     */
    public class Pool {
        private static final int MAX_AVAILABLE = 100;
        private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
    
        public Object getItem() throws InterruptedException {
            available.acquire();
            return getNextAvailableItem();
        }
    
        public void putItem(Object x) {
            if (markAsUnused(x))
                available.release();
        }
    
        // Not a particularly efficient data structure; just for demo
        protected Object[] items = new Object[MAX_AVAILABLE];
        protected boolean[] used = new boolean[MAX_AVAILABLE];
    
        protected synchronized Object getNextAvailableItem() {
            for (int i = 0; i < MAX_AVAILABLE; ++i) {
                if (!used[i]) {
                    used[i] = true;
                    return items[i];
                }
            }
            return null; // not reached
        }
    
        protected synchronized boolean markAsUnused(Object item) {
            for (int i = 0; i < MAX_AVAILABLE; ++i) {
                if (item == items[i]) {
                    if (used[i]) {
                        used[i] = false;
                        return true;
                    } else
                        return false;
                }
            }
            return false;
        }
    
    }
  • 相关阅读:
    获取html页面传递过来的参数
    jqueryWeiui+pagehelper滚动加载(实现分页)
    【JS】js随笔
    【Java】Java基础
    【FrameWork】Hibernate
    【FrameWork】Struts2
    去掉inline-block间的间隙
    javascript单例模式
    关于call/apply与bind的一点误解
    git笔记-常用命令
  • 原文地址:https://www.cnblogs.com/leodaxin/p/7701340.html
Copyright © 2011-2022 走看看