Semaphore
1) 正常的锁(concurrent.locks或synchronized锁)在任何时候都只允许一个任务访问一项资源,而
java.util.concurrent.Semaphore计数信号量允许n个任务同时访问该资源,可以把信号量看成是向外分发使用资源的许可证;
2)对象池概念:对象池管理数量有限的对象,当要使用对象时可以签出他们,而在用户使用完毕时,可以将它们签回,这种功能可以封装在一个泛型类中:
class Pool<T>{
private Semaphore avaliable; //管理计数信号量
private List<T> items = new ArrayList<T>(); //管理对象列表
private volatile boolean[] checkOut; //管理对象列表上相应下标的对象的签出情况
private int size;
public Pool(Class<T> classObject,int size){
this.size = size;
checkOut = new boolean[size];
available = new Semaphore(size);
for(int i=0;i<size;i++){
try{
items.add(classObject.newInstance());
}catch(Exception e){
throw new RunTimeException(e);
}
}
}
public T checkOut() throw InterruptedException{ //签出对象池的信号量
available.acquire();
return getItem();
}
public T getItem(){
for(int i=0;i<size;i++){
if(!checkOut[i]){
checkOut[i] =true;
return item.get(i);
}
}
}
public void checkIn(T x){ //签入对象池的信号量
if(releaseItem(x))
available.release();
}
public boolean releaseItem(T x){
int index = items.indexOf(x);
if(index == -1)
retrun false;
if(checkOut[index]){
checkOut[idnex] = false;
return true;
}
return false;
}
}
//Test
class Demo(){
}
class CheckOutWorker<T> implements Runnable{
priavte Pool<T> pool;
public CheckOutWorker(Pool<T> pool){ this.pool = pool; }
public void run(){
try{
T item = pool.checkOut();
<using item to do something>
pool.checkIn(item);
}catch(Interruptedexception ex){
}
}
/*or 记录所有已被签出的对象,返回对象列表供主程使用
priavte Pool<T> pool;
private List<T> checkOutList = new ArrayList<T>();
public CheckOutWorker(Pool<T> pool){ this.pool = pool;this.checkOutList = checkOutList; }
public void run(){
try{
T item = pool.checkOut();
checkOutList.add(item);
<using checkOutList to do something>
pool.checkIn(item);
checkOutList.remove(item);
}catch(Interruptedexception ex){
}
}*/
}
class Driver{
void main(){
Pool<Demo> pool = new Pool(Demo.class,N);
ExecutorService exec = Executors.newChacedTheadPool();
for(int i=0;i<N;i++)
exec.execute(new CheckOut(pool));
exec.shoudown();
}
}