1 public class GCtest {
2 /**
3 *
4 * 任何对象的finalize方法只会被系统自动调用一次
5 *
6 * */
7
8 public static GCtest gctest = null;
9
10 public void isAlive(){
11 System.out.println("yes ! i am still alive :) ");
12 }
13
14 @Override
15 protected void finalize() throws Throwable {
16 // TODO Auto-generated method stub
17 super.finalize();
18 System.out.println("finalize mehtod executed");
19 GCtest.gctest = this;
20 }
21
22 public static void main(String[] args) throws Exception {
23 // TODO Auto-generated method stub
24 gctest = new GCtest();
25 //第一次自救
26 gctest = null;
27 System.gc();
28 //finalize 优先等级比较低
29 Thread.sleep(500);
30 if(gctest != null){
31 gctest.isAlive();
32 }else{
33 System.out.println("yes ! i am dead :(");
34 }
35
36 //第二次自救 代码一样 但失败了
37 gctest = null;
38 System.gc();
39 //finalize 优先等级比较低
40 Thread.sleep(500);
41 if(gctest != null){
42 gctest.isAlive();
43 }else{
44 System.out.println("yes ! i am dead :(");
45 }
46
47
48 }
49
50 }