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;
        }
    
    }
  • 相关阅读:
    使用jQuery对象
    jQuery插件
    使用jQuery函数
    jQuery的两把利器
    初始jQuery
    BOM——特效
    BOM的介绍
    DOM——节点操作
    miaov- 自动生成正V反V大于号V小于号V楼梯等图案
    H5 -- 本地存储计数器的值 和前端校验用户
  • 原文地址:https://www.cnblogs.com/leodaxin/p/7701340.html
Copyright © 2011-2022 走看看