码迷,mamicode.com
首页 > 其他好文 > 详细

JDK文档中关于Semaphore的正确使用以及使用场景

时间:2017-10-20 21:45:54      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:syn   except   span   amp   UI   bsp   err   rup   number   

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

}

 

JDK文档中关于Semaphore的正确使用以及使用场景

标签:syn   except   span   amp   UI   bsp   err   rup   number   

原文地址:http://www.cnblogs.com/leodaxin/p/7701340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!