java编程思想-第五章-某些练习题

10&11

finalize()被调用的条件, (1)类未被调用(置null), (2)调用System.gc().
注意: Java1.6以下可以, 1.8不可以.

//: Main.java

/**
 * 垃圾回收
 * 注意: Java环境1.6可以, 1.8不可以, 垃圾回收机制改变.
 */

class Test { @Override protected void finalize(){ System.out.println("finalize"); // super.finalize();  } } class Main { public static void main(String[] args) { Test t = new Test(); t = null; // 确保finalize()会被调用  System.gc(); } } /** * Output: finalize *///:~

12

清理对象时, 会调用finalize()函数, 并且会保留存储数据, 如T2;
在清理对象时, 会入栈出栈, 先入后清理, 后入先清理.

//: Main.java

/**
 * 垃圾回收
 * 注意: Java环境1.6可以, 1.8不可以, 垃圾回收机制改变.
 */

class Tank { boolean isFull = false; String name; Tank(String name) { this.name = name; } void setEmpty() { isFull = false; } void setFull() { isFull = true; } @Override protected void finalize(){ if (!isFull) { System.out.println(name + ": 清理"); } // super.finalize();  } } class Main { public static void main(String[] args) { Tank t1 = new Tank("T1"); Tank t2 = new Tank("T2"); Tank t3 = new Tank("T3"); t1.setFull(); t2.setEmpty(); t1 = null; t2 = null; t3 = null; System.gc(); } }
/** * Output: T3: 清理 T2: 清理 *///:~
 

猜你喜欢

转载自www.cnblogs.com/lijingran/p/8997777.html