如何finalize方法和shutdownHooks互动

来源:互联网 发布:二次元直播软件 编辑:程序博客网 时间:2024/05/22 16:39

 public class ShutdownDemo {
  public static void main(String[] argsthrows Exception {

    // Create an Object with a finalize() method.
    Object f = new Object() {
      public void finalize() {
        System.out.println"Running finalize()");
      }
    };

    // Add a shutdownHook to the JVM
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        System.out.println("Running Shutdown Hook");
      }
    });

    // Unless the user puts -f (for "free") on the command line,
    // call System.exit while holding a reference to 
    // Object f, which can therefore not be finalized().

    if (args.length == && args[0].equals("-f")) {
      f = null;
      System.gc();
    }

    System.out.println("Calling System.exit()");
    System.exit(0);
  }
}

原创粉丝点击