首页 > 代码库 > Java--Runtime.addShutdownHook

Java--Runtime.addShutdownHook

转自:http://kim-miao.iteye.com/blog/1662550

一.Runtime.addShutdownHook理解

在看别人的代码时,发现其中有这个方法,便顺便梳理一下。

void java.lang.Runtime.addShutdownHook(Thread hook)

该方法用来在jvm中增加一个关闭的钩子。当程序正常退出,系统调用 System.exit方法或虚拟机被关闭时才会执行添加的shutdownHook线程。其中shutdownHook是一个已初始化但并不有启动的线程,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作。  

 

二.示例代码

 

 1 public class TestRuntimeShutdownHook {
 2     public static void main(String[] args) {
 3 
 4         Thread shutdownHookOne = new Thread() {
 5             public void run() {
 6                 System.out.println("shutdownHook one...");
 7             }
 8         };
 9         Runtime.getRuntime().addShutdownHook(shutdownHookOne);
10 
11         Runnable threadOne = new Runnable() {
12             public void run() {
13                 try {
14                     Thread.sleep(1000);
15                 } catch (InterruptedException e) {
16                     e.printStackTrace();
17                 }
18                 System.out.println("thread one doing something...");
19             }
20         };
21 
22         Runnable threadTwo = new Thread() {
23             public void run() {
24                 try {
25                     Thread.sleep(2000);
26                 } catch (InterruptedException e) {
27                     e.printStackTrace();
28                 }
29                 System.out.println("thread two doing something...");
30             }
31         };
32 
33         threadOne.run();
34         threadTwo.run();
35     }
36 }

 

  

输出如下:

 

1 thread one doing something...  
2 thread two doing something...  
3   
4 shutdownHook one...  

 

Java--Runtime.addShutdownHook