当前位置: 代码迷 >> J2SE >> 关于fianlize的有关问题,搞不懂
  详细解决方案

关于fianlize的有关问题,搞不懂

热度:205   发布时间:2016-04-24 12:38:07.0
关于fianlize的问题,搞不懂
Java code
class T{    boolean empty=false;    T(boolean status){empty=status;}    void dropout(){empty=true;}        protected void finalize(){                if (empty==false)            System.out.println("error:the tank is still not empty!");            }}public class Tank {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub                T tank1=new T(false);        T tank2=new T(false);        tank1.dropout();        System.runFinalization();        System.gc();            }}


为什么error:the tank is still not empty这句话没有被打印出来呢?

------解决方案--------------------
打印不出来error:the tank is still not empty的原因是
1.lz的代码中没有需要回收的对象,就是说内存中没有垃圾,即便你运行gc也不会去执行finalize()方法
2.tank1.dropout(); 调用之后,把empty变成true了,怎莫能打印出来呢,不知道lz为什莫要这样设计

说一点题外话
System.runFinalization();
这个不会马上去调用finalize(),只是当内存空间不足时才会由jvm去调用finalize()
所以,只有System.gc();才是强制调用finalize()

帮楼主改了一下代码,仅供参考
Java code
class T{    boolean empty=false;    T(boolean status){empty=status;}    void dropout(){empty=true;}        protected void finalize() throws Throwable{        [color=#FF0000]System.out.println("the end");[/color]                if (empty==false)            System.out.println("error:the tank is still not empty!");    }}public class Tank {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub                T tank1=new T(false);        //new T(false); //把这个注释去掉的话,就使内存中产生了一个可能被回收的对象                tank1.dropout(); //不写这句话就能打印出error...        tank1=null;        //System.runFinalization();        System.gc();    }}
  相关解决方案