class Person{
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return "姓名" +this.name+"年龄"+this.age;
}
public void finalize() throws Throwable{
System.out.println(this);
}
}public class SystemDemo { public static void main(String[] args) {
Person per=new Person("好样的",20);
per=null;
System.gc();
System.out.println("好样的");//1
}}上面的程序是测试finalize()方法,在main()方法中实例化对象后又强制断开,当直接调用JVM回收垃圾时,如果去掉//1,
finalize()方法不会输出,而增加//1后,就能输出toString()的返回值了,这是为什么????
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return "姓名" +this.name+"年龄"+this.age;
}
public void finalize() throws Throwable{
System.out.println(this);
}
}public class SystemDemo { public static void main(String[] args) {
Person per=new Person("好样的",20);
per=null;
System.gc();
System.out.println("好样的");//1
}}上面的程序是测试finalize()方法,在main()方法中实例化对象后又强制断开,当直接调用JVM回收垃圾时,如果去掉//1,
finalize()方法不会输出,而增加//1后,就能输出toString()的返回值了,这是为什么????
好样的
姓名好样的年龄20
因为:System.gc();是运行垃圾回收器垃圾回收器,可是JVM调用finalize() 是不定时的,即使你用System.gc();通知JVM让回收垃圾,但它不一定马上调用,具体是么时候调用垃圾回收机制,那由JVM决定,是不定时的,也与java的运行环境有关系。
增加这句输出的,finalize()也会被调用,JVM怎样判定调用finalize()方法的??
Person per=new Person("好样的",20);
per=null;System.gc();//第一次标记,把new Person("好样的",20)这个对象加入F-Queue队列中
System.out.println("好样的");//1
try{
Thread.sleep(500);//因为Finalizer线程优先级低,所以让主线程等它0.5秒
}catch(InterruptedException e){
}
System.gc();//第二次标记,没有引用,删掉此对象
}