ShutdownHook

java.lang.Runtime
addShutdownHook

public void addShutdownHook(Thread hook)
Registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  •  

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

     

  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

Example:

 

addShutdownHook(getShutdownHook());

protected void addShutdownHook(final Thread hook) {
        getRuntime().addShutdownHook(hook);
    }

private Thread getShutdownHook() {
        return new Thread(new Runnable() {

}}

 

 

Java程序中,可以通过添加关闭钩子(Shutdown Hook)来实现在程序退出时关闭资源和平滑退出的功能。关闭钩子是通过调用Runtime类的addShutdownHook(Thread hook)方法来注册的。当程序退出时,关闭钩子可以在多种场景下被调用,包括程序正常退出、使用System.exit()方法、终端使用Ctrl+C触发的中断、系统关闭以及使用Kill pid命令干掉进程等情况。\[2\] 具体到停止线程的问题,关闭钩子本身并不能直接停止线程。关闭钩子主要用于在程序退出时执行一些清理操作,例如关闭资源、保存数据等。如果需要停止线程,可以通过其他方式来实现,例如使用线程的interrupt()方法来中断线程的执行,或者使用标志位来控制线程的运行状态。关闭钩子可以在程序退出时执行这些停止线程的操作,但本身并不直接负责停止线程。\[2\] 需要注意的是,在使用关闭钩子时,应该谨慎处理资源的关闭和线程的停止,以确保程序能够正常退出并释放资源。同时,关闭钩子的执行顺序是不确定的,因此在编写关闭钩子的代码时,应该考虑到可能的并发和竞争条件,以避免出现意外的问题。\[2\]\[3\] #### 引用[.reference_title] - *1* [ShutdownHook - java中优雅地停止服务](https://blog.csdn.net/zhipengfang/article/details/117451139)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [ShutdownHook Java优雅地停止服务](https://blog.csdn.net/fututadeyoushang/article/details/80941632)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值