package untitled14;
/**
* This application is to demo how an applcation end
*/
public class Test {
public Test() {}
public static void main(String[] args) {
Test test1 = new Test();
//.................
System.out.PRintln("hello world");
//Do something before system exit
System.exit(0);//也可以不写这句代码,让程序自然结束。
}
}
对于简单的应用系统,我们直接可以在System.exit(0)代码执行前,添加需要在应用程序退出前需要完成的工作,如:关闭网络连接,关闭数据库连接等。 /*****************************************************************************
本程序仅演示,如何在Java应用程序中添加系统退出事件处理机制
*****************************************************************************/
package untitled14;
import java.util.*;
import java.io.*;
/**
* This application is used to demo how to hook the event of an application
*/
public class Untitled1 {
public Untitled1() {
doShutDownWork();
}
/***************************************************************************
* This is the right work that will do before the system shutdown
* 这里为了演示,为应用程序的退出增加了一个事件处理,
* 当应用程序退出时候,将程序退出的日期写入 d:/t.log文件
**************************************************************************/
private void doShutDownWork() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
FileWriter fw = new FileWriter("d://t.log");
System.out.println("Im going to end");
fw.write("the application ended! " + (new Date()).toString());
fw.close();
}
catch (IOException ex) {
}
}
});
}
/****************************************************
* 这是程序的入口,仅为演示,方法中的代码无关紧要
***************************************************/
public static void main(String[] args) {
Untitled1 untitled11 = new Untitled1();
long s = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
//在这里增添您需要处理代码
}
long se = System.currentTimeMillis();
System.out.println(se - s);
}
}
在上述程序中,我们可以看到通过在程序中增加Runtime.getRuntime().addShutdownHook(new Thread()) 事件监听,捕捉系统退出消息到来,然后,执行我们所需要完成工作,从而使我们的程序更健壮!
新闻热点
疑难解答