Runtime.getRuntime().addShutdownHook(

Runtime.getRuntime().addShutdownHook(
 这个方法的含义说明:
    这个方法的意思就是在jvm中增加一个关闭的钩子,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。
测试类如下:
  1. public class RunTimeTest {
  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. Thread thread1 = new Thread() {
  7. public void run() {
  8. System.out.println("thread1...");
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. public void run() {
  13. System.out.println("thread2...");
  14. }
  15. };
  16. Thread shutdownThread = new Thread() {
  17. public void run() {
  18. System.out.println("shutdownThread...");
  19. }
  20. };
  21. Runtime.getRuntime().addShutdownHook(shutdownThread);
  22. thread1.start();
  23. thread2.start();
  24. }
  25. }

打印结果为:
thread2...
thread1...
shutdownThread...

或者:
thread2...
thread1...
shutdownThread...

结论:
无论是先打印thread1还是thread2,shutdownThread 线程都是最后执行的(因为这个线程是在jvm执行关闭前才会执行)。

你可能感兴趣的:(Runtime.getRuntime().addShutdownHook()