使用关闭钩子进程杀死jar实例(kill <PID>)后不会被杀死

时间:2019-10-07 10:12:52

标签: 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 个答案:

答案 0 :(得分:4)

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

相关问题