一.多线程基本篇-1.11 钩子程序

1.使用场景

  • 当程序正常退出,系统调用 System.exit方法
  • 虚拟机被关闭时
  • 程序抛出异常时
  • 可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作

通过我们的程序中运行完之后都会进行一些清理工作,比如关闭数据库资源,同步等操作。这时我们的钩子函数addShutdownHook有了用武之地。

2.用法

Runtime.getRuntime().addShutdownHook(Thread thread)

3.实战

public
 class CaptureException{
    public static void main(String[] args){
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("The application will exit");
            notifyAndRelease();
        } ));
        
        int i = 0;
        while (true){
             try{
                 Thread.sleep(1_000L);
             }catch(Throwable e){
               //ignore
             }
             System.out.println("I am working...");             
             i++;
             if (i > 20) throw new RuntimeException("error");
        }

    }
   
    public static void notifyAndRelease(){
       System.out.println("notify to the admin");
       try{
            Thread.sleep(1_000L);
       }catch(Throwable e){
         //ignore
       }
       System.out.println("Will release resource(file,socket,connections)");
       try{
            Thread.sleep(1_000L);
       }catch(Throwable e){
         //ignore
       }

       System.out.println("Release done");
     
          
    }
} 


-------------------------------------------------------------------------------------------
kill 128964
[root@localhost java]# java -cp . CaptureException
I am working...
...
I am working...

The application will exit
notify to the admin
I am working...
Will release resource(file,socket,connections)
I am working...
Exception in thread "main" java.lang.RuntimeException: error
        at CaptureException.main(CaptureException.java:17)
Release done
-------------------------------------------------------------------------------------------        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值