package FinalizeTest;
public class Person {
public Person(){
System.out.println("person created");
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
System.out.println("gc ");
throw new Exception("no effect");
}
}
package FinalizeTest;
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person per = new Person();
per = null;
System.gc();
System.out.println("hello world");
}
}
输出为
person created
hello world
gc
代码如上所示, 求解释为什么hello world
会在gc之前输出??
关于java的
finalize()
不要与c/c++混淆了,java程序员从来不能决定垃圾回收的时机。官方描述:
finalize()
只是定义了回收时的动作,但具体何时回收仍旧由垃圾回收器自己决定。仔细看下javadoc