protected abstract Object creat();
protected abstract void close(Object obj);
方法即可。小弟我乃java初学者,程序虽然能用,但可能写得很幼稚,还请各位高手指教一下。
get()从池中获取对象
free()把对象还回池中
clear()清洗池
getObjectCount()获取池中存在的对象数目
getActiveObjectCount()获取目前在池外工作的对象数目
elements()获取池中所有对象的数组
package huzq.Pools;
import java.util.*;
public abstract class Pool{
private Vector buffer;
private int objectCount;
private int maxObject;
public Pool(int maxObject){
this.maxObject = maxObject;
objectCount = 0;
buffer = new Vector(maxObject);
}
protected abstract Object creat();
protected abstract void close(Object obj);
private Object _get(){
Object obj = null;
if (buffer.isEmpty()){
if (objectCount < maxObject){
obj = creat();
objectCount++;
}
}else{
obj = buffer.elementAt(0);
buffer.removeElementAt(0);
}
return obj;
}
public Object get(){
Object obj = _get();
synchronized(this){
while(obj == null){
Thread.yield();
try{wait();}catch(Exception e){}
obj = _get();
}
notifyAll();
}
return obj;
}
public synchronized void free(Object obj){
buffer.addElement(obj);
notifyAll();
}
public synchronized void setMaxSize(int maxSize){
clear();
this.maxObject = maxSize;
buffer.setSize(maxSize);
}
public int getObjectCount(){
return objectCount;
}
public int getActiveObjectCount(){
return objectCount - buffer.size();
}
public synchronized void clear(){
if (buffer.isEmpty())
return;
while(getActiveObjectCount() > 0){
Thread.yield();
try{wait();}catch(Exception e){}
}
Object[] e = elements();
for(int i=0; i
buffer.removeAllElements();
objectCount = 0;
notifyAll();
}
public synchronized Object[] elements(){
if (buffer.isEmpty()){
return null;
}
while(getActiveObjectCount() > 0){
Thread.yield();
try{wait();}catch(Exception e){}
}
Object[] o = new Object[objectCount];
Enumeration e = buffer.elements();
int i = 0;
while(e.hasMoreElements()){
o = e.nextElement();
i++;
}
return o;
}
}
做完这个对象池,如何让其保存在内存中多用户共享??
> 做完这个对象池,如何让其保存在内存中多用户共享??
使用静态的对象,但是要注意安全,或者使用ThreadLocal