The source code:
package basic;
public class finalizeTest {
private String name;
public void finalize(a){
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();
/* The newly created object instance does not have any variables pointing to it, so it will be recycled after system.gc () is called * and you can see that the Scala instance executes finalize method on a thread that is not the main thread, so the printed thread ID is different * */
new finalizeTest("Scala"); System.gc(); }}Copy the code
Printout:
Main Thread id: 1
finalize called: Scala
Thread id in finalize: 3
Copy the code