我有一个带有关闭钩子的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");
}
}
}
答案 0 :(得分:4)
您在关机钩子线程中使用了 System.exit(0)
。删除它的关闭挂钩,以便该进程可以正常终止。实际上, System.exit(0)
本身在内部调用shutdown,因此代码可能处于死锁状态。