finalize 方法使用案例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package test; class TestGC { private String str = "hello" ; TestGC(String str) { this .str = str; } public void finalize() { System.out.println(str); } } public class Hello { /** * @param args */ public static void main(String[] args) { // TODO 自動生成方法存根 System.out.println( "hello" ); TestGC test = new TestGC( "test1" ); test = new TestGC( "test2" ); test = null ; //注釋掉這一句,test1被回收。加上則先回收test2,后test1 System.gc(); } } |
finalize() 方法是在 Object 類中定義的,因此所有的類都繼承了它。子類覆蓋 finalize() 方法以整理系統資源或者執行其他清理工作。finalize() 方法是在垃圾收集器刪除對象之前對這個對象調用的。
以上就是關于Java垃圾回收finalize()的用法介紹,希望對大家的學習有所幫助。