更新時間:2022-08-02 10:00:17 來源:動力節點 瀏覽1355次
Java結束進程的流程是什么?動力節點小編來告訴大家。java1.8之后,Process有了destroy和destroyForcibly方法,用來結束進程,一般結束進程的流程為:
terminate process with destroy()
allow process to exit gracefully with reasonable timeout
kill it with destroyForcibly() if process is still alive
但是在java1.8的實現中,下面是源碼:
public Process destroyForcibly(){
destroy();
return this;
}
可以看到destroyForcibly和destroy是等效的,這樣就有一個問題,如果一段時間后destroy無法關閉進程,那么destroyForcibly又怎么能保證能強制關閉進程呢?除此之外,如果新進程又開啟了一個新的子進程,又如何關閉新的子進程呢?(雖然這是新進程的責任,但是在'強制關閉'的情況下,新進程應該無法保證能順利的關閉子進程)。
在java9+中,Process有了一個新的方法:toHandle,可以獲取到 ProcessHandle對象,這個對象也有 destroy和destroyForcibly這兩個方法,看了下它們的實現,是一個native方法
private static native boolean destroy0(long pid, long startTime, boolean forcibly);
應該比Process的更加可靠,至少強制關閉看起來不再是自欺欺人,而ProcessHandle還提供了一個children方法:
Returns a snapshot of the current direct children of the process.The parent of a direct child process is the process.Typically, a process that is not alive has no children.
這個方法可以獲取進程的直接子進程,通過
p.children().forEach(ProcessHandle::destroy);
可以關閉它的直接子進程。如果這還不夠,還有一個descendants方法,可以返回直接子進程以及子進程的子進程。
Returns a snapshot of the descendants of the process.The descendants of a process are the children of the processplus the descendants of those children, recursively.Typically, a process that is not alive has no children.
所以java9以及以后
ProcessHandle handle = p.toHandle();
handle.destroy();
handle.descendants().forEach(ProcessHandle::destroy);
應該是更好的關閉方法。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習