在執行System.gc()時,也會執行finalize()
覆寫finalize()範例 ##ReadMore##
public class MyObject {
static int count;
MyObject() {
++count;
}
public static void main(String[] args) {
MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject();
MyObject obj3 = new MyObject();
System.out.println("目前有" +count+ "個物件");
obj2 = null;
System.out.println("請求G.C.");
System.gc();
System.out.println("目前剩餘" +count+ "個物件");
}
protected void finalize() throws Throwable {
--count;
String tName = Thread.currentThread().getName();
System.out.println("執行finalize()的是:" + tName);
}
}
執行結果:
目前有3個物件
請求G.C.
執行finalize()的是:Finalizer
目前剩餘2個物件
0 意見 :
張貼留言