为Java应用程序添加退出事件响应_MySQL
一个完整的Java应用程序,通常至少要有一个应用程序的结束点。对于一般程序来说,系统开发者根据需要和个人的偏好,会在程序结束位置,通过添加System.exit(0),或System.out(-1),来结束程序,或不加这些指令,让程序自然运行到结束。
如:下列典型代码
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对应用程序的退出的事件出处理机制。
对当前应用程序对象的获得,Java通过Runtime静态方法:Runtime.getRuntime()通过Runtime的 void addShutdownHook(Thread hook) 法向Java虚拟机注册一个shutdown钩子事件,这样一旦程序结束事件到来时,就运行线程hook,我们在实际应用时候,只要将程序需要完成之前做的一些工作直接通过线程hook来完成。具体演示代码如下:
/*****************************************************************************
本程序仅演示,如何在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 //在这里增添您需要处理代码
}
long se = System.currentTimeMillis();
System.out.println(se - s);
}
}
在上述程序中,我们可以看到通过在程序中增加Runtime.getRuntime().addShutdownHook(new Thread()) 事件监听,捕获系统退出消息到来,然后,执行我们所需要完成工作,从而使我们的程序更健壮!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

If you encounter the Unable to save changes error while using the Photos app for image editing in Windows 11, this article will provide you with solutions. Unable to save changes. An error occurred while saving. Please try again later. This problem usually occurs due to incorrect permission settings, file corruption, or system failure. So, we’ve done some deep research and compiled some of the most effective troubleshooting steps to help you resolve this issue and ensure you can continue to use the Microsoft Photos app seamlessly on your Windows 11 device. Fix Unable to Save Changes to Photos App Error in Windows 11 Many users have been talking about Microsoft Photos app error on different forums

In Windows, the Photos app is a convenient way to view and manage photos and videos. Through this application, users can easily access their multimedia files without installing additional software. However, sometimes users may encounter some problems, such as encountering a "This file cannot be opened because the format is not supported" error message when using the Photos app, or file corruption when trying to open photos or videos. This situation can be confusing and inconvenient for users, requiring some investigation and fixes to resolve the issues. Users see the following error when they try to open photos or videos on the Photos app. Sorry, Photos cannot open this file because the format is not currently supported, or the file

The Apple Vision Pro headset is not natively compatible with computers, so you must configure it to connect to a Windows computer. Since its launch, Apple Vision Pro has been a hit, and with its cutting-edge features and extensive operability, it's easy to see why. Although you can make some adjustments to it to suit your PC, and its functionality depends heavily on AppleOS, so its functionality will be limited. How do I connect AppleVisionPro to my computer? 1. Verify system requirements You need the latest version of Windows 11 (Custom PCs and Surface devices are not supported) Support 64-bit 2GHZ or faster fast processor High-performance GPU, most

Microsoft Paint not working in Windows 11/10? Well, this seems to be a common problem and we have some great solutions to fix it. Users have been complaining that when trying to use MSPaint, it doesn't work or open. Scrollbars in the app don't work, paste icons don't show up, crashes, etc. Luckily, we've collected some of the most effective troubleshooting methods to help you resolve issues with Microsoft Paint app. Why doesn't Microsoft Paint work? Some possible reasons why MSPaint is not working on Windows 11/10 PC are as follows: The security identifier is corrupted. hung system

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

Users can get various wallpapers by using wallpaperengine. Many users don't know why the wallpapers are gone after wallpaperengine exits. Dynamic wallpapers can only run on the desktop when the software you installed the wallpaper is turned on. Why are the wallpapers gone after wallpaperengine exits? 1. Dynamic wallpapers can only run on the desktop when the software you installed the wallpaper is turned on. 2. WallpaperEngine overwrites the original wallpaper, and of course it will be gone when you exit. 3. The wallpaper is still there after it is turned off, unless the file format is an image type, which can be obtained through some means, but it is not dynamic. 4. There is no video or dynamic image as a wall in Windows.
