简体   繁体   English

如何用线程和锁静默地终止Java程序

[英]How to silently termintate a Java program with threads and locks

In C programs using system threads for example, I can pass a SIGINT with Ctrl+C and the process will be killed silently. 例如,在使用系统线程的C程序中,我可以通过Ctrl+C传递SIGINT,该过程将被静默杀死。 But when I do the same thing to a Java program with threads, locks, semaphores et cetera, the JVM just stops there and I have to kill the process "outside", by closing the terminal or rebooting the system. 但是,当我对带有线程,锁,信号量等的Java程序执行相同的操作时,JVM只是停在那里,并且我必须通过关闭终端或重新启动系统来终止进程“外部”。 How can a make a Java program silently exit as it should without closing the terminal when I see some wrong behaviors in runtime? 当我在运行时看到一些错误的行为时,如何使Java程序静默退出而不关闭终端?

You can add a shutdown hook to the JVM that gets triggered when a SIGINT is received and then in there call Runtime.getRuntime().halt(0). 您可以向在收到SIGINT时触发的JVM添加一个关闭挂钩,然后在其中调用Runtime.getRuntime()。halt(0)。 That will kill the process. 那会杀死进程。 You can even use the Shutdown Hook to clean your running Threads. 您甚至可以使用Shutdown Hook清理正在运行的线程。

[EDIT] My initial answer was to use System.exit() in the hook. [编辑]我的最初答案是在挂钩中使用System.exit()。 But that will not work because System.exit will trigger the already running hook. 但这将不起作用,因为System.exit将触发已经运行的钩子。

You can try this example with the hook and not registering the hook. 您可以使用该挂钩尝试该示例,而不注册该挂钩。

public class Exit {

public static void main(String[] args) {

    Runtime.getRuntime().addShutdownHook(new ExitHok());

    Thread t = new Thread(new Printer());
    t.start();

}

private static class ExitHok extends Thread {
    @Override
    public void run() {
        System.out.println("Received shutdown");
        Runtime.getRuntime().halt(0);
    }
}

private static class Printer implements Runnable {
    @Override
    public void run() {
        int counter = 0;
        while (true) {
            System.out.println(++counter);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM