java 優雅退出

package com.hhly.game.test;java

import java.util.concurrent.TimeUnit;linux

import sun.misc.Signal;
import sun.misc.SignalHandler;windows

public class ShutDownGracefully implements SignalHandler{ide

    private static String getOSSignalType(){
        return System.getProperties().getProperty("os.name").toLowerCase().startsWith("win") ? "INT" : "USR2";
    }oop

     public static void main(String[] args) throws InterruptedException {  
            Signal sig = new Signal(getOSSignalType());  
            Signal.handle(sig, new ShutDownGracefully());
            Object o = new Object();
            synchronized (o) {
                o.wait(10000);
              }
            Runtime.getRuntime().exit(0);
     }進程

    @Override
    public void handle(Signal signalName) {
        invokeShutdownHook();
        
    }  
    private void invokeShutdownHook(){
        Thread t = new Thread(new ShutdownHook(), "ShutdownHook-Thread");
        Runtime.getRuntime().addShutdownHook(t);
     }
}
class ShutdownHook implements Runnable{
    @Override
    public void run() {
        System.out.println("ShutdownHook execute start...");
        System.out.print("Netty NioEventLoopGroup shutdownGracefully...");
        try {
            TimeUnit.SECONDS.sleep(10000);//模擬應用進程退出前的處理操做
        } catch (InterruptedException e) {
                e.printStackTrace();
        }
        System.out.println("ShutdownHook execute end...");
    System.out.println("Sytem shutdown over, the cost time is 10000MS");
        }
}
 get

 

windows 運行後 按ctrl+c, linux  kill -12 pidit

相關文章
相關標籤/搜索