Runtime.getRuntime().addShutdownHook(Thread);
//addShutdownHook是指,增加JVM停止时要做处理事件。当JVM停止时,就会把之前增加的这些HOOK逐个运行。
运行这个例子可以简单体会到它的作用.
package Thread;
public class Thread1 extends Thread{
  public void run() {
    int i=0;
    while(i<10){
      try {
        Thread.sleep(2000);
      }
      catch (InterruptedException ex) {
      }
      System.out.println("~Thread 1~");
      i++;
    }
  }
}
package Thread;
public class Thread2 extends Thread{
  public void run() {
    int i=0;
    while(i<10){
      try {
        Thread.sleep(1000);
      }
      catch (InterruptedException ex) {
      }
      System.out.println("~Thread 2~");
      i++;
    }
  }
}
package Thread;
public class Thread3 extends Thread{
  public void run(){
    System.out.println("---end---");
  }
}
package Thread;
public class  addShutdownHookTest{
  public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread3());
    Thread1 t1 = new Thread1();
    t1.start();
    Thread2 t2 = new Thread2();
    t2.start();
  }

相关文章:

  • 2022-12-23
  • 2021-12-31
  • 2021-08-20
  • 2022-01-13
  • 2021-11-12
  • 2021-10-07
  • 2022-12-23
猜你喜欢
  • 2021-07-25
  • 2021-06-26
  • 2022-12-23
  • 2021-07-19
  • 2021-06-20
相关资源
相似解决方案