完成器的使用

示范如何定义和使用一个完成器方法的类:
 1 /** A Java class to demonstrate how a finalizer
 2  * method is defined and used
 3  */

 4 public   class  FinalizerClass  {
 5
 6   private int a, b;
 7
 8   /** Class default constructor method */
 9   public FinalizerClass() {
10      a = 1;
11      b = 2;
12      System.out.println( "Constructing an object!" );
13   }

14
15   /** Class finalizer method
16     * @exception Throwable Any exception at all
17     */

18   protected void finalize() throws Throwable {
19      System.out.println( "Doing object cleanup!" );
20   }

21
22   /** Test method for the class
23     * @param args Not used
24     */

25   public static void main( String[] args ) {
26      FinalizerClass x = new FinalizerClass();
27      FinalizerClass y = new FinalizerClass();
28      x = null//强制将对象设置为无用单元
29      y = null;
30      System.gc();  //无用单元收集
31      System.runFinalization();   //运行完成器
32   }

33}

运行结果为:
Constructing an object!
Constructing an object!
Doing object cleanup!
Doing object cleanup!

你可能感兴趣的:(使用)