Runtime.getRuntime().addShutdownHook(Thread)

public class Demo {
    public static void main(String[] args) {
        
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
               System.out.println("run thread3");
            }
            
        });
        
        new th2().start();
        
        
        new th1().start();
    
        
    }
    
    static class th1 extends Thread{
        @Override
        public void run() {
            System.out.println("run thread1");
            super.run();
        }
    }
    
    static class th2 extends Thread{
        @Override
        public void run() {
            System.out.println("run thread2");
            super.run();
        }
    }
    
}

在jvm退出之前,会执行所有通过addShutdownHook方法添加的线程,执行完了之后退出jvm。

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