Java基础-finalize
finalize方法在对象被垃圾收集器析构(回收)之前调用,一般用来清除回收对象。
Java的内存回收是由JVM来自动完成。若需要手动使用,则可以使用finalize方法。
protected void finalize()
{
// 在这里清除回收对象
}
Demo
public class Test {
public static void main(String[] args) {
Tests t1 = new Tests(1);
Tests t2 = new Tests(2);
Tests t3 = new Tests(3);
t1 = t2 = null;
System.gc(); // 调用Java垃圾收集器
}
}
class Tests {
private int id;
public Tests(int id) {
this.id = id;
System.out.println("Tests " + id + " is created");
}
protected void finalize() throws java.lang.Throwable {
super.finalize();
System.out.println("Tests " + id + " is disposed");
}
}