class Chair
{
public static long created = 0;
public static long finalized = 0;
public static boolean gcrun = false;
public static boolean f = false;
public long i = 0; Chair(){
i = ++created;
if (i == 1)
{
System.out.println("Creating start!");
}
//System.out.print(".");
}
public void finalize(){
finalized++;
//System.out.print("-"); if (!gcrun)
{
gcrun = true;
System.out.println("Finalized start!");
}
if (i == 47)
{
f = true;
System.out.println("finalized 47 chair,"+created+" created,stop create!");
} if (finalized >= created)
{
System.out.println("All chair is finalized!");
}
}
}public class Gc
{
public static void main(String args[]){
while(Chair.f == false){
new Chair();
new String("take a few space");
}
System.out.println(Chair.created+" chair created,"+Chair.finalized+" chair finalized!");
System.out.println("Bye");
}
}1.看了think in java中关于gc和finalize的介绍,根据书上的例子写了这个程序,但是发现All chair is finalized一直在打印出来,就是说一直在调用finalize,这让我很不解,哪位帮我看看,是什么原因2.我如果把注解的部分打开,有可以得到正常结果,非常奇怪.JDK是1.4.2先谢谢大家了.
{
public static long created = 0;
public static long finalized = 0;
public static boolean gcrun = false;
public static boolean f = false;
public long i = 0; Chair(){
i = ++created;
if (i == 1)
{
System.out.println("Creating start!");
}
//System.out.print(".");
}
public void finalize(){
finalized++;
//System.out.print("-"); if (!gcrun)
{
gcrun = true;
System.out.println("Finalized start!");
}
if (i == 47)
{
f = true;
System.out.println("finalized 47 chair,"+created+" created,stop create!");
} if (finalized >= created)
{
System.out.println("All chair is finalized!");
}
}
}public class Gc
{
public static void main(String args[]){
while(Chair.f == false){
new Chair();
new String("take a few space");
}
System.out.println(Chair.created+" chair created,"+Chair.finalized+" chair finalized!");
System.out.println("Bye");
}
}1.看了think in java中关于gc和finalize的介绍,根据书上的例子写了这个程序,但是发现All chair is finalized一直在打印出来,就是说一直在调用finalize,这让我很不解,哪位帮我看看,是什么原因2.我如果把注解的部分打开,有可以得到正常结果,非常奇怪.JDK是1.4.2先谢谢大家了.
print()方法相对比较耗时间.不过在我机器上,如果把两个print方法都注释掉的话,程序有一定几率会出正确结果,其他情况会导致程序一直运行下去,没出现像你说的那样All chair is finalized.
finalize是不定期调用的。
自动回收没有引用的对象,即这个对象存在但没有任何引用
而且是没有规律的
(C) 版权所有 1985-2001 Microsoft Corp.D:\project\sjava\L4>java Gc.class
Creating start!
Finalized start!
finalized 47 chair,45458 created,stop create!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
All chair is finalized!
以上是我运行的结果.如果所有的创造对象已经finalize了,怎么会还有finalize呢,奇怪了.难道一个对象会重复finalize?
我试了下,有这个问题。
你的逻辑有问题把。
,
结束标志改成if (i >= 47),
就可以了,我试过了。