linux kill命令下如何优雅的退出java程序

 实现SignalHandler

kill命令常用信号(之后代码会用到):

HUP     1    终端断线
INT     2    中断(同 Ctrl + C)
QUIT    3    退出(同 Ctrl + \)
TERM   15    终止
KILL    9    强制终止
CONT   18    继续(与STOP相反, fg/bg命令)
STOP   19    暂停(同 Ctrl + Z)

SignalHandler实现类

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

public class KillHandler implements SignalHandler {

	/**
	 * HUP 1 终端断线 INT 2 中断(同 Ctrl + C) QUIT 3 退出(同 Ctrl + \) TERM 15 终止 KILL 9
	 * 强制终止 CONT 18 继续(与STOP相反, fg/bg命令) STOP 19 暂停(同 Ctrl + Z)
	 */
	public static final String TERM_15 = "TERM";

	public static final String QUIT_3 = "QUIT";

	public void registerSignal(String signalName) {
		Signal signal = new Signal(signalName);
		Signal.handle(signal, this);
	}

	@Override
	public void handle(Signal signal) {
		if (signal.getName().equals(TERM_15)) {
			TestThread.shutdownFlag = true;
			System.out.println("shutdownFlag=true");
			// System.exit(0);
		} else if (signal.getName().equals(QUIT_3)) {
			// TODO do something
		}
	}

}

main类

public class TestThread {
	public static boolean shutdownFlag = false;
	public static void main(String[] args) {
		
		KillHandler killHandler = new KillHandler();
        killHandler.registerSignal(KillHandler.TERM_15);
        
		int i = 0;
		while (true) {
			System.out.println(i);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;
			if(shutdownFlag)break;
		}
		try {
			System.out.println("main Thread sleep 5s");
			Thread.sleep(1000*5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("main Thread exit");
	}
}

应用

运行main类,执行kill xxx,java程序会先执行实现类的handle方法,然后main方法运行完,释放资源,程序关闭。

ps:main类执行完才能释放资源,像while(true)这种循环必须打断才能释放资源。


你可能感兴趣的:(java)