【问题标题】:How to shutdown JVM if one thread crashes in a multithreaded environment?如果一个线程在多线程环境中崩溃,如何关闭 JVM?
【发布时间】:2016-02-10 16:02:21
【问题描述】:

我有一个 Java 程序,它看起来像这样:

public static void main(final String[] args) {

    Thread t1 = new ComplicatedThread1();
    Thread t2 = new ComplicatedThread2();
    Thread t3 = new ComplicatedThread3();

    t1.start();
    t2.start();
    t3.start();

}

每个线程都包含很多不是我写的代码。 一个线程中可能有多个子线程。 如果恰好一个线程崩溃(即抛出未捕获的运行时异常),则会出现最大的问题。在这种情况下,整个程序仍在运行,但它 出现故障。

现在鉴于我无法让每个线程都万无一失,我想在任何线程崩溃时完全关闭 JVM。

问题:如何在主程序中捕获any线程引发的运行时异常并要求系统关闭?

【问题讨论】:

    标签: java multithreading jvm


    【解决方案1】:

    在主程序的顶部添加几行:

    public static void main(final String[] args) {
    
        // Making sure that if one thread crashes,
        // then the whole JVM will shut down.
        Thread.setDefaultUncaughtExceptionHandler(new Thread.
            UncaughtExceptionHandler() {
                public void uncaughtException(Thread t, Throwable e) {
                    System.out.println(t + " throws exception: " + e);
                    System.exit(1);
                }
            });
    
        // Do anything you want from here
        ....
    }
    

    这将启动 JVM 的关闭过程。请注意,某些活动线程可能仍会运行一段时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      相关资源
      最近更新 更多