2010-06-04 70 views

回答

26

你可以添加一个shutdown hook做任何清理。

像这样:

public class myjava{ 
    public static void main(String[] args){ 
     Runtime.getRuntime().addShutdownHook(new Thread() { 
     @Override 
      public void run() { 
       System.out.println("Inside Add Shutdown Hook"); 
      } 
     }); 

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

     System.out.println(5/0);  //Operating system sends SIGFPE to the JVM 
            //the JVM catches it and constructs a 
            //ArithmeticException class, and since you 
            //don't catch this with a try/catch, dumps 
            //it to screen and terminates. The shutdown 
            //hook is triggered, doing final cleanup. 
    } 
} 

然后运行它:

[email protected]:~$ javac myjava.java 
[email protected]:~$ java myjava 
Shut Down Hook Attached. 
Exception in thread "main" java.lang.ArithmeticException:/by zero 
     at myjava.main(myjava.java:11) 
Inside Add Shutdown Hook 
+3

博客条目是404 – luckydonald 2017-01-19 12:44:05

4

另一种方式来处理信号Java是通过sun.misc.signal包。了解如何使用它,请参阅http://www.ibm.com/developerworks/java/library/i-signalhandling/

注意: sun。*软件包中的功能也意味着它可能在所有操作系统中都不可移植/行为相同。但你可能想尝试一下。

+0

但事实上,它也是一样的吗? – 2010-06-07 09:39:18

+1

不是 - 不完全是。我提到的信号处理API可用于处理Java应用程序中的大部分Native OS信号(陷阱,内联,终止等)。 另一方面,ShutdownHook只有在JVM最终终止时(在收到终止信号后)才会被调用。 – arcamax 2010-06-14 08:41:11

+0

@arcamax链接似乎被破坏 – GreenGiant 2013-10-23 21:56:36