1/** 2 * when no reference is available, the lifecycle ends and becomes garbage. 3 * The finalize () method is automatically called for all objects before they are recycled. 4 *************************************** * ************ 5 * an object will not be recycled immediately after it becomes garbage, 6 * The JVM will detect the accumulation of garbage in the memory to a certain extent before it will be recycled. 7 * if we don't want to wait until then, 8 * can use System. gc () method to notify the virtual machine to recycle garbage. 9 * after this method is called, The JVM will start a new thread to process the garbage, which takes some time. 10 */11 public class GcDemo {12 13 public static void main (String [] args) throws Exception {14 15 for (int I = 0; I <1000; I ++) {16 new Person (); // after an object is created, it is not used as garbage 17} 18 System. out. println ("before recycling:" + Person. count); 19 System. gc (); // notify the virtual machine to recycle garbage 20/* 21 * call System. after gc (), the JVM starts a new thread to process garbage. It takes a certain amount of time for the JVM to sleep for a few seconds, check the effect of garbage collection. 22 * It takes up to 23 */24 threads for garbage collection. sleep (1000); 25 System. out. println ("after recycling:" + Person. count); 26} 27 28} 29 30 class Person {31 // define a count to count, view 32 public static int count before and after collection; 33 34 public Person () {35 count ++; // each time an object is created, count Plus 36} 37 // all objects automatically call the finalize () method 38 public void finalize () before being recycled () {39 count --; // clear a garbage and subtract a 40} 41}