2010-06-04 44 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