今天同事問我,一個jar包,啟動起來,端口正常,而且防火墻全都關閉了,為什么前臺訪問出錯?
我第一反應是啟動是否正常,然后就是阿里云安全組有沒有配置對應的端口。
后來發現自己也不對,是因為kill -9的問題,所以本文就是來探究kill指令和java的關閉鉤子
1. Java的原生關閉鉤子
直接使用這個,不管使用什么方式停止程序,都不會調用關閉鉤子,
不知道自己哪里出錯,希望大佬指正。
public class RunTest { public static void main(String[] args) throws InterruptedException { int i = 1; while (i<10000) { System.out.println(i); i++; Thread.sleep(1000); } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.out.println("I'll be back"); } })); } }
1.1 使用IDE關閉調試
可以看到,我用IDE點擊運行,然后關閉,就直接停止了,沒有調用關閉鉤子。
1.2 使用kill -15 指令
1.3 使用kill -9 指令
終于有位大佬提出了質疑,
說需要把關閉鉤子注冊方法寫到while循環上面,
這樣才能注冊成功,于是我就試了一下,
事就這樣成了。
感謝 a塵 博主的指導。
修改后代碼:
public class RunTest { public static void main(String[] args) throws InterruptedException { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.out.println("I'll be back"); } })); int i = 1; while (i<10000) { System.out.println(i); i++; Thread.sleep(1000); } } }
這時候用IDE測試,用debug模式停止是正常的:
在linux環境,使用kill -15:
在linux環境,使用kill -9:
2. SpringBoot關閉鉤子
測試jar包下載地址:
關閉鉤子測試jar包
import org.springframework.beans.factory.DisposableBean; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class ApplicationListens implements CommandLineRunner, DisposableBean { @Override public void destroy() throws Exception { System.out.println("銷毀程序------"); } @Override public void run(String... args) throws Exception { System.out.println("運行程序------"); } }
2.1 使用IDE關閉
2.2 使用kill -15 指令
2.3 使用kill -9 指令
所以,如果想優雅的關閉應用,需要用kill -15 ,
但是有時候我們會遇到關閉掉的情況,
那只能用kill -9
參考文獻:
SpringBoot-監聽應用啟動與關閉的回調鉤子
到此這篇關于Kill指令停掉Java程序的思考的文章就介紹到這了,更多相關Kill指令停掉Java程序內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/WeiHao0240/article/details/120849403