gpt4 book ai didi

java - 使用关闭 Hook 进程杀死 jar 实例(kill )后未被杀死

转载 作者:行者123 更新时间:2023-11-30 06:40:23 25 4
gpt4 key购买 nike

我有一个带有关闭钩子(Hook)的 Java 程序。我运行它,然后用 kill <PID> 终止正在运行的进程.通过这样做,关闭 Hook 得到执行,相关线程立即停止。但该进程仍在后台运行。那么这里可能是什么问题?

过程:

  1. javac InfiniteLoop.java

  2. java InfiniteLoop

  3. 对于 PID,jps -ml | grep 'InfiniteLoop'

  4. 杀死 <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");
}
}
}

最佳答案

您在关闭 Hook 线程中使用了 System.exit(0)。删除它的关闭 Hook ,以便进程正常终止。实际上,System.exit(0) 本身会在内部调用关闭,因此代码可能处于死锁状态。

关于java - 使用关闭 Hook 进程杀死 jar 实例(kill <PID>)后未被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com