标签:
test1:
public class TestClass { int flage = 0; TestClass(int flage){ System.out.println("new Object TestClass"); this.flage = flage; } @Override protected void finalize() { System.out.println("run this method:finalize() And this flag is " + flage); } public static void main(String[] args) { TestClass t = new TestClass(2); System.gc(); } }输出结果:
new Object TestClass
test2:
public class TestClass { int flage = 0; TestClass(int flage){ System.out.println("new Object TestClass"); this.flage = flage; } @Override protected void finalize() { System.out.println("run this method:finalize() And this flag is " + flage); } public static void main(String[] args) { TestClass t = new TestClass(2); t = null; System.gc(); } }输出结果:
new Object TestClass
run this method:finalize() And this flag is 2test3:
public class TestClass { int flage = 0; TestClass(int flage){ System.out.println("new Object TestClass"); this.flage = flage; } @Override protected void finalize() { System.out.println("run this method:finalize() And this flag is " + flage); } static void test(){ TestClass t = new TestClass(3); } public static void main(String[] args) { TestClass t = new TestClass(2); test(); System.gc(); } }输出结果:
new Object TestClass
new Object TestClass
run this method:finalize() And this flag is 3
1.对象:作用域一般是最近的一个花括号内部 .出了作用域,该对象仍继续占据内存空间,但我们无法访问该对象。
2.finalize()方法:垃圾回收器准备释放内存的时候,会先调用finalize(),并且在下一次垃圾回收动作发生时,才会真正回收对象占用的内存。
3.System.gc()方法:该方法只是向垃圾回收器建议回收内存,不一定会真正回收内存。
4.当一个垃圾回收器判断一个对象不在作用域内或者为null时,垃圾回收器就回收该对象的内存(调用finalize方法)。所以会发生test1、test2、test3.(还没有真正了解垃圾回收器,所以单论程序来说了,垃圾回收器以后会写)。
标签:
原文地址:http://www.cnblogs.com/maying3010/p/5838961.html