本帖最后由 徐梦侠 于 2012-10-19 14:52 编辑
如果不含代码stu=new Student("李四");System.out.println(stu.toString());,打印结果就是Finalize Object : Student : 张三。
说明空间已经释放,那应该先打印Finalize Object : Student : 张三,可为什么结果不是这样呢?
class Student{
private String name;
public Student(String name){
this.name = name;
}
public String toString(){
return("Student : " + this.name);
}
public void finalize() throws Throwable{
System.out.println("Finalize Object : " + this);
}
}
class SystemDemo02{
public static void main(String[] args){
Student stu = new Student("张三");
stu = null; //断开引用
//如果让线程等待1分钟,即运行一段时间,再运行系统垃圾回收就会调用fianlize方法了
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.gc(); //强制释放空间
stu=new Student("李四");
System.out.println(stu.toString());
}
}
为什么打印结果会是:
Student : 李四
Finalize Object : Student : 张三
|