package initialization;
class Tank {
static int counter;
int id = counter++;
boolean full;
public Tank() {
System.out.println("Tank " + id + " created");
full = true;
}
public void empty() { full = false; }
protected void finalize() {
if(full)
System.out.println(
"Error: tank " + id + " must be empty at cleanup");
else
System.out.println("Tank " + id + " cleaned up OK");
}
public String toString() { return "Tank " + id; }
}
public class E12_TankWithTerminationCondition {
public static void main(String args[]) {
new Tank().empty();
new Tank();
// Don't empty the second one
System.gc(); // Force finalization?
System.runFinalization();
}
} /* Output:
Tank 0 created
Tank 1 created
Error: tank 1 must be empty at cleanup
Tank 0 cleaned up OK
*///:~
关于finalize方法的问题,求解释代码
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
小小病魔 2019-03-26 16:37关注System.gc()是java中的垃圾回收机制,通过该方法调用提醒java虚拟机回收不用的对象,此时虚拟机会调用销毁对象的finalize()方法
解决 无用评论 打赏 举报