protected void finalize() {
// 对象的清理工作
}
public class Counter {
private static int count = 0; // 计数器变量
public Counter() {
// 构造方法
this.count++; // 创建实例时增加值
}
public int getCount() {
// 获取计数器的值
return this.count;
}
protected void finalize() {
// 析构方法
this.count--; // 实例销毁时减少值
System.out.println("对象销毁");
}
}
2)创建一个带 main() 的 TestCounter 类对计数器进行测试,示例代码如下:
public class TestCounter {
public static void main(String[] args) {
Counter cnt1 = new Counter(); // 建立第一个实例
System.out.println("数量:"+cnt1.getCount()); // 输出1
Counter cnt2 = new Counter(); // 建立第二个实例
System.out.println("数量:"+cnt2.getCount()); // 输出2
cnt2 = null; // 销毁实例2
try {
System.gc(); // 清理内存
Thread.currentThread().sleep(1000); // 延时1000毫秒
System.out.println("数量:"+cnt1.getCount()); // 输出1
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
执行后输出结果如下:
数量:1 数量:2 对象销毁 数量:1技巧:由于 finalize() 方法的不确定性,所以在程序中可以调用 System.gc() 或者 Runtime.gc() 方法提示垃圾回收器尽快执行垃圾回收操作。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有