源代码:
package basic;
public class finalizeTest {
private String name;
public void finalize(){
System.out.println("finalize called: " + this.name);
System.out.println("Thread id in finalize: " + Thread.currentThread().getId());
}
public finalizeTest(String name){
this.name = name;
}
public static void main(String[] args) {
System.out.println("Main Thread id: " + Thread.currentThread().getId());
finalizeTest test = new finalizeTest("Jerry");
test.hashCode();
/* 这个新创建出来的对象实例没有任何变量指向它,因此System.gc()调用之后就会被回收
* 而且能发现Scala实例执行finalize方法的线程并不是主线程,打印出的线程ID不一样
* */
new finalizeTest("Scala");
System.gc();
}
}
打印输出:
Main Thread id: 1
finalize called: Scala
Thread id in finalize: 3