当前线程”在调用wait()/notify()时,必须拥有该对象的同步锁 高并发使用对象池实例
1,初始化对象池,3个对象
2,获取对象并移除 同步锁
3,释放对象,通知等待获取对象的线程,同步锁
public class PoolUtils {
private List<Domain> list;
public void init(){
list = new ArrayList<Domain>();
for(int i = 0; i < 3; i++){
list.add(new Domain());
}
}
public synchronized Domain getDomain(){
Domain domain = null;
if(list.size()>0){
domain = list.remove(0);
System.out.println(Thread.currentThread().getName()+",get left:"+list.size());
} else {
try {
System.out.println(Thread.currentThread().getName()+":wait before");
wait();
System.out.println(Thread.currentThread().getName()+":wait after");
} catch (Exception e) {
System.out.println("getException:"+e.getMessage());
e.printStackTrace();
}
domain = getDomain();
}
return domain;
}
public synchronized void returnDomain(Domain domain){
list.add(domain);
System.out.println(Thread.currentThread().getName()+",return left:"+list.size());
notifyAll();
// notify();
}
}
public static void main(String[] args) {
final PoolUtils pu = new PoolUtils();//单例
pu.init();
Thread t1 = new Thread(){
public void run(){
Domain dom = pu.getDomain();
System.out.println(Thread.currentThread().getName()+":get domain:"+dom);
try {
Thread.currentThread().sleep(3000);
} catch (Exception e) {
System.out.println("getExceptionT:"+e.getMessage());
e.printStackTrace();
}
pu.returnDomain(dom);
System.out.println(Thread.currentThread().getName()+":return domain:"+dom);
}
};
Thread t2 = new Thread(){ 。。。。。。。。。
原文:https://www.cnblogs.com/xingminghui111/p/12390963.html