【问题标题】:Implementation of addShutdownHookaddShutdownHook 的实现
【发布时间】:2014-10-09 06:10:06
【问题描述】:

在没有 main 方法的类中,哪里以及如何实现 addShutdownHook?这可以用来杀死该类初始化的所有活动套接字吗?

【问题讨论】:

  • 你有没有看过:stackoverflow.com/questions/8722826/…这不是真正的重复,但我认为你可以在那里学到东西?另外:hellotojavaworld.blogspot.se/2010/11/…
  • @SamuelÅslund:感谢您的帮助..我已经搜索过,但没有找到此链接..
  • @SamuelÅslund:当我们在 linux 中使用 Kill -9 命令杀死服务器时,addShutdownHook 不起作用。还有其他相同的解决方案吗??
  • 不,kill -9 的全部意义在于,被杀死的程序在死亡之前根本不允许做任何事情。要了解有关 kill 命令的更多信息,“signal”和“kill”可能是很好的 google 关键字

标签: java


【解决方案1】:

这可能对你有用,

   public class AddShutdownHookSample {
      public void attachShutDownHook(){
           Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                      System.out.println("Inside Add Shutdown Hook");
                }
           });

           System.out.println("Shut Down Hook Attached.");
      }
   }

在main方法中:

public static void main(String[] args) {
  AddShutdownHookSample sample = new AddShutdownHookSample();
  sample.attachShutDownHook();
  System.out.println("Last instruction of Program....");
  System.exit(0);
 }

描述你正在尝试做的整个事情,并指出你遇到问题的确切点,这样其他人会更容易帮助你。

【讨论】:

  • @Atmaram 我找不到你,你的意思是我们可以在其他静态函数上做同样的事情吗?那么答案是肯定的。
  • 我是说如果我将这部分代码添加到我们类的静态块中......它会工作吗?
  • 像这样完成... static { Runtime.getRuntime().addShutdownHook ( new Thread() { public void run() { server.shutdown(); } } ); }
【解决方案2】:

下面是一个例子,这可能对你有帮助

public class RuntimeDemo {

   // a class that extends thread that is to be called when program is exiting
 static class Message extends Thread {

  public void run() {
     System.out.println("Bye.");
  }
}

public static void main(String[] args) {
  try {

     // register Message as shutdown hook
     Runtime.getRuntime().addShutdownHook(new Message());

     // print the state of the program
     System.out.println("Program is starting...");

     // cause thread to sleep for 3 seconds
     System.out.println("Waiting for 3 seconds...");
     Thread.sleep(3000);

     // print that the program is closing 
     System.out.println("Program is closing...");


  } catch (Exception e) {
     e.printStackTrace();
  }
 }
}

【讨论】:

    【解决方案3】:

    就这样……

     static { 
             Runtime.getRuntime().addShutdownHook ( new Thread() { 
                   public void run() { 
                       server.shutdown(); 
                   } 
              } ); 
      }
    

    【讨论】:

      猜你喜欢
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多