获取有关Java进程终止的通知 [英] Get notification on a Java process termination
本文介绍了获取有关Java进程终止的通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个控制台Java应用程序应该运行,直到它被Ctrl + C停止或关闭控制台窗口。如何将该应用程序编程为在退出之前执行清理代码?
There is a console Java application which is supposed to run untill it is stopped by Ctrl+C or closing the console window. How that application can be programmed to execute a clean up code before exit?
推荐答案
你可以使用关机挂钩。
基本上你需要创建一个执行关机的线程操作,然后将其添加为关闭挂钩。例如:
Basically you need to create a Thread which will perform your shutdown actions, and then add it as a shutdown hook. For example:
class ShutdownHook extends Thread
{
public void run()
{
// perform shutdown actions
}
}
// Then, somewhere in your code
Runtime.getRuntime().addShutdownHook(new ShutdownHook())
这篇关于获取有关Java进程终止的通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文