windows Java钩子,Java线程和关闭钩子

当JVM正常或突然关闭时, 关闭钩子可用于执行清理资源或保存状态。执行干净的资源意味着关闭日志文件, 发送一些警报或其他内容。因此, 如果要在JVM关闭之前执行一些代码, 请使用shutdown挂钩。

JVM什么时候关闭?

在以下情况下, JVM将关闭:

用户在命令提示符下按ctrl + c

调用System.exit(int)方法

用户注销

用户关闭等

addShutdownHook(Thread hook)方法

Runtime类的addShutdownHook()方法用于在虚拟机中注册线程。句法:

public void addShutdownHook(Thread hook){}

可以通过调用静态工厂方法getRuntime()获得Runtime类的对象。例如:

运行时r = Runtime.getRuntime();

工厂方法

返回类实例的方法称为工厂方法。

关机钩的简单示例

class MyThread extends Thread{

public void run(){

System.out.println("shut down hook task completed..");

}

}

public class TestShutdown1{

public static void main(String[] args)throws Exception {

Runtime r=Runtime.getRuntime();

r.addShutdownHook(new MyThread());

System.out.println("Now main sleeping... press ctrl+c to exit");

try{Thread.sleep(3000);}catch (Exception e) {}

}

}

Output:Now main sleeping... press ctrl+c to exit

shut down hook task completed..

注意:可以通过调用Runtime类的halt(int)方法来停止关闭序列。

匿名类的关机挂钩示例相同:

public class TestShutdown2{

public static void main(String[] args)throws Exception {

Runtime r=Runtime.getRuntime();

r.addShutdownHook(new Thread(){

public void run(){

System.out.println("shut down hook task completed..");

}

}

);

System.out.println("Now main sleeping... press ctrl+c to exit");

try{Thread.sleep(3000);}catch (Exception e) {}

}

}

Output:Now main sleeping... press ctrl+c to exit

shut down hook task completed..

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值