class Chair{
static boolean gcrun=false;
static boolean f=false;
static int created=0;
static int finalized=0;
int i;
Chair(){
i=++created;
if(created==47)
System.out.println("Created 47");
}
public void finalize(){
if(!gcrun){
gcrun=true;
System.out.println("Beginning to finalize after"+created+"Chairs have been created");
}
if(i==47){
System.out.println("Finalizing Chair #47,"+"Setting flag to stop Chair creation");
f=true;
}
finalized++;
if(finalized>=created)
System.out.println("All"+finalized+"finalized");
}
}
public class Garbage {
public static void main(String[] args){
while(!Chair.f){
new Chair();
new String("To take up space");
}
System.out.println("After all Chairs have been created:\n"+"Total created="+Chair.created+",total finalized="+Chair.finalized);
if(args.length>0){
if(args[0].equals("gc")||
args[0].equals("all")){
System.out.println("gc():");
System.gc();
}
if(args[0].equals("finalize")||args[0].equals("all")){
System.out.println("runFinalization():");
System.runFinalization();
}
}
System.out.println("bye");
}
}
书上的例子 关于垃圾回收调用finalize()函数的 结果如下
Created 47
Beginning to finalize after4791Chairs have been created
Finalizing Chair #47,Setting flag to stop Chair creation
After all Chairs have been created:
Total created=33530,total finalized=6264
bye
既然finalize()函数是在静态变量created=4791被调用的 怎么后面出现了Finalizing Chair #47,Setting flag 也就是i==47满足条件 是怎么回事啊 。。[ 此贴被霓棠烟鱼在2007-11-04 18:03重新编辑 ]