Mat*_*hen 60
是的,你可以注册一个关机钩子Runtime.addShutdownHook()
.
Edw*_*ale 39
您可以添加一个关闭钩子来进行任何清理.
像这样:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
然后运行它:
el@apollo:~$ javac myjava.java
el@apollo:~$ 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
Run Code Online (Sandbox Code Playgroud)
在Java中处理信号的另一种方法是通过sun.misc.signal包.请参阅http://www.ibm.com/developerworks/java/library/i-signalhandling/以了解如何使用它.
注意: sun.*包中的功能也意味着它可能不是所有操作系统中的可移植/行为相同.但你可能想尝试一下.
归档时间: |
|
查看次数: |
37587 次 |
最近记录: |