首页 > 代码库 > 对象的销毁(finalize()方法)

对象的销毁(finalize()方法)

当生成的对象数量大于一定的程度的时候自动启动gc:

 1 class ToFinalize{
 2   protected void finalize() throws Throwable{
 3     System.out.println("销毁对象");
 4   }
 5 }
 6 public class DoFinalize{
 7   public static void main(String[] args){
 8     while(true){
 9       new ToFinalize();
10     }
11   }
12 }

强制启动gc:

 1 class ToFinalize {
 2     protected void finalize() throws Throwable {
 3         System.out.println("销毁对象");
 4     }
 5 }
 6 
 7 public class DoFinalize {
 8     public static void main(String[] args) {
 9         new ToFinalize();
10         System.gc();
11     }
12  }

 

对象的销毁(finalize()方法)