有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

停止jar实例(kill<PID>)和关闭挂钩进程后的java不会停止

我有一个带有关闭挂钩的Java程序。我运行它,然后用kill <PID>终止正在运行的进程。通过这样做,关闭钩子被执行,相关线程立即停止。但该过程仍在后台运行。那么这里有什么问题呢

过程:

  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");
    }
  }
}

共 (1) 个答案

  1. # 1 楼答案

    您已经在关机挂钩线程中使用了System.exit(0)。移除它的关机钩子,使进程正常终止。实际上,System.exit(0)本身在内部调用shutdown,因此代码可能处于死锁状态