最后附上源代码
public class Demo {
//统计创建的对象数量
private static int count=0;
//常量来设置最多能创建的对象数量
private static final int LIMIT=10;
private Demo() {
//这里面写什么自己看情况
}
public static Demo getDemo() {
if(count
count++;
return new Demo();
}else {
return null;
}
}
@Override
protected void finalize() throws Throwable {
count--;
}
public static void main(String[] args) {
for(int i=0;i<20;i++) {
Object a=getDemo();
if(i%2==0) {
a=null;
}
System.out.println(a);
}
}
}