Semaphore

一个有界的容器:

/一个有界的集合Set
class BoundedhashSet<T> {
    private final Set<T> set;
    private final Semaphore sem;

    public BoundedhashSet(int count) {
        this.sem = new Semaphore(count);
        this.set = new CopyOnWriteArraySet<T>();
    }

    public boolean add(T o) throws InterruptedException {
        //获取信号量,如果不成功就阻塞
        sem.acquire();

        //这样写,不好,如果set.add()不成功需要释放一个信号量
//        if(set.add(o))
//            return true;
//
//        return false;


        boolean isadded = false;
        try{
            if(set.add(o)){
                isadded = true;
                return isadded;
            }
        }finally {
            if(!isadded)
                sem.release();
        }
        return isadded;
    }

    public boolean remove(T o ){
        boolean isremoved = false;
        if(set.remove(o)){
            sem.release();
            return isremoved;
        }
        return isremoved;
    }
}

 

posted @ 2018-11-27 19:05  式微胡不归  阅读(104)  评论(0编辑  收藏  举报