用信号量semaphore构建有界阻塞容器

package com.cn;

import java.util.*;
import java.util.concurrent.Semaphore;

public class BoundedHashSet<T> {
	private final Set<T> set;
	private final Semaphore sem;
	
	public BoundedHashSet(int bound){
		this.set = Collections.synchronizedSet(new HashSet<T>());
		sem = new Semaphore(bound);
	}
	
	public boolean add(T o) throws InterruptedException{
		sem.acquire();
		boolean wasAdded = false;
		try{
			wasAdded = set.add(o);
			return wasAdded;
		}finally{
			if(!wasAdded){
				sem.release();
			}
		}
	}
	
	public boolean remove(Object o){
		boolean wasRemoved = set.remove(o);
		if(wasRemoved){
			sem.release();
		}
		return wasRemoved;
	}
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		final BoundedHashSet<String> pool = new BoundedHashSet<String>(5);
	
		for(int i = 0; i < 6; i++){
			Thread thread = new Thread(new Worker(String.valueOf(i),pool));
			thread.start();
		}
		Thread.currentThread().sleep(2000);
		Thread thread = new Thread(new Worker2(String.valueOf(2),pool));
		thread.start();
	}
	
}
class Worker implements Runnable{
	private final String s ;
	final BoundedHashSet<String> pool;
	public Worker(String s,BoundedHashSet<String> pool){
		this.s = s;
		this.pool = pool;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			pool.add(s);
			System.out.println("set "+ s);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

class Worker2 implements Runnable{
	private final String s ;
	final BoundedHashSet<String> pool;
	public Worker2(String s,BoundedHashSet<String> pool){
		this.s = s;
		this.pool = pool;
	}
	@Override
	public void run() {
		pool.remove(s);
		System.out.println("remove "+ s);
	}
	
}

猜你喜欢

转载自elena-me.iteye.com/blog/2316002