Think in java 答案

    技术2022-05-11  125

    阅前声明: http://blog.csdn.net/heimaoxiaozi/archive/2007/01/19/1487884.aspx

    /****************** Exercise 13 ****************** Create a class called Tank that can be filled* and emptied, and has a death condition that it* must be empty when the object is cleaned up.* Write a finalize() that verifies this death* condition. In main(), test the possible* scenarios that can occur when your Tank is* used.***********************************************/class Tank {  static int counter = 0;  int id = counter++;  boolean full = falsepublic Tank() {    System.out.println("Tank " + id + " created");    full = true;  }  public void empty() {    full = false;  }  protected void finalize() {    if(full)      System.out.println(        "Error: tank " + id +        " must be empty at cleanup");    else      System.out.println(        "Tank " + id + " cleaned up OK");  }  public String toString() {    return "Tank " + id;  }}public class E13_TankWithDeathCondition {  public static void main(String args[]) {    new Tank().empty();    new Tank();    // Don't empty the second one    System.gc(); // Force finalization?  }}

    //+M java E13_TankWithDeathCondition

    **Note that I intentionally did not create references of type Tank, because then those references would be in scope when System.gc( ) was called and they wouldn’t be cleaned up and thus they wouldn’t be finalized (another option is to explicitly set references to zero when you want them to be garbage collected – try it by modifying the above example).

    **The output is:

    Tank 0 createdTank 1 createdTank 0 cleaned up OKError: tank 1 must be empty at cleanup

    **Because you can’t be sure finalizers will be called, they have only a limited use and this is one of them – checking the state of objects when they do get run, to ensure they’ve been cleaned up properly.

     


    最新回复(0)