停止jar实例(kill<PID>)和关闭挂钩进程后的java不会停止
我有一个带有关闭挂钩的Java程序。我运行它,然后用kill <PID>
终止正在运行的进程。通过这样做,关闭钩子被执行,相关线程立即停止。但该过程仍在后台运行。那么这里有什么问题呢
过程:
javac InfiniteLoop.java
java InfiniteLoop
对于PID,
jps -ml | grep 'InfiniteLoop'
杀死
<PID>
public class InfiniteLoop {
static boolean isInfinte = true;
public static void main(String[] args) throws InterruptedException {
Thread myThread = new MyShutDownHook();
Runtime.getRuntime().addShutdownHook(myThread);
while (isInfinte) {
Thread.sleep(3000);
System.out.println("Loop is running");
}
System.out.println("Loop Exited");
myThread.interrupt();
}
}
class MyShutDownHook extends Thread {
@Override
public void run() {
System.out.print("Got Kill Message so stopping application");
InfiniteLoop.isInfinte = false;
boolean currentLoopStatus = true;
while (currentLoopStatus) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.print("Got Intteruption");
currentLoopStatus = false;
e.printStackTrace();
System.exit(0);
}
System.out.println("Child Thread Running");
}
}
}
# 1 楼答案
您已经在关机挂钩线程中使用了
System.exit(0)
。移除它的关机钩子,使进程正常终止。实际上,System.exit(0)
本身在内部调用shutdown,因此代码可能处于死锁状态