java編程思想-第五章-某些練習題
阿新 • • 發佈:2018-05-06
編程 class 垃圾回收機制 sdn 被調用 out stat ride string
參考https://blog.csdn.net/caroline_wendy/article/details/46844651
10&11
finalize()被調用的條件
Java1.6以下的條件:
(1)類未被調用(置null)(2)調用System.gc()
1.8的條件:
(1)調用System.gc().(在調用了System.gc()之後,finalize()才被執行,也就是在執行最後一個 ‘}’時,finalize()才被執行)
//: Main.java
/**
* 垃圾回收
* 註意: Java環境1.6可以, 1.8不可以, 垃圾回收機制改變.
*/
class Test {
@Override
protected void finalize(){
System.out.println("finalize");
// super.finalize();
}
}
class Main {
public static void main(String[] args) {
Test t = new Test();
t = null; // 確保finalize()會被調用
System.gc();
}
}
/**
* Output:
finalize
*///:~
12
清理對象時, 會調用finalize()函數, 並且會保留存儲數據, 如T2;
在清理對象時, 會入棧出棧, 先入後清理, 後入先清理.
//: Main.java
/**
* 垃圾回收
* 註意: Java環境1.6可以, 1.8不可以, 垃圾回收機制改變.
*/
class Tank {
boolean isFull = false;
String name;
Tank(String name) {
this.name = name;
}
void setEmpty() {
isFull = false;
}
void setFull() {
isFull = true;
}
@Override
protected void finalize(){
if (!isFull) {
System.out.println(name + ": 清理");
}
// super.finalize();
}
}
class Main {
public static void main(String[] args) {
Tank t1 = new Tank("T1");
Tank t2 = new Tank("T2");
Tank t3 = new Tank("T3");
t1.setFull();
t2.setEmpty();
t1 = null;
t2 = null;
t3 = null;
System.gc();
}
}
/**
* Output:
T3: 清理
T2: 清理
*///:~
java編程思想-第五章-某些練習題