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. //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()) 事件監聽,捕捉系統退出消息到來,然后,執行我們所需要完成工作,從而使我們的程序更健壯!
新聞熱點
疑難解答