您的位置:首页 > 编程语言 > Java开发

java 优雅退出

2016-07-12 00:00 190 查看
摘要: netty使用的也是如此

package com.hhly.game.test;

import java.util.concurrent.TimeUnit;

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

public class ShutDownGracefully implements SignalHandler{

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

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");
}
}

windows 运行后 按ctrl+c, linux kill -12 pid
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java优雅退出