美文网首页Java-多线程
system.exit(0) 和 system.exit(1)

system.exit(0) 和 system.exit(1)

作者: Djbfifjd | 来源:发表于2021-03-05 11:35 被阅读0次

一、简述

java.lang.System源码,方法说明如下:

/**
     * Terminates the currently running Java Virtual Machine. The
     * argument serves as a status code; by convention, a nonzero status
     * code indicates abnormal termination.
     * <p>
     * This method calls the <code>exit</code> method in class
     * <code>Runtime</code>. This method never returns normally.
     * <p>
     * The call <code>System.exit(n)</code> is effectively equivalent to
     * the call:
     * <blockquote><pre>
     * Runtime.getRuntime().exit(n)
     * </pre></blockquote>
     *
     * @param      status   exit status.
     * @throws  SecurityException
     *        if a security manager exists and its <code>checkExit</code>
     *        method doesn't allow exit with the specified status.
     * @see        java.lang.Runtime#exit(int)
     */
    public static void exit(int status) {
    Runtime.getRuntime().exit(status);
    }

二者都是用来结束当前正在运行中的 JVM,退出程序的意思,如果 status 是非零参数,那么表示是非正常退出。

区别:

  1. system.exit(0):程序正常执行结束退出。该方法是将整个虚拟机里的内容都停掉了 ,而 dispose() 只是关闭这个窗口,但是并没有停止整个 application exit() 。无论如何,内存都释放了。也就是说连 JVM 都关闭了,内存里根本不可能还有什么东西。

  2. system.exit(1):是非正常退出,就是说无论程序正在执行与否,都退出。1 或者说非 0 表示非正常退出程序。不管 status 为何值都会退出程序。return 是回到上一层,而System.exit(status)是回到最上层。

二、用法

在 if-else 判断中,如果程序按照预想的执行,到最后需要停止程序,那么使用System.exit(0)。而System.exit(1)一般放在 catch 块中,当捕获到异常,用来停止程序。这个 status=1 是用来表示这个程序是非正常退出。

相关文章

网友评论

    本文标题:system.exit(0) 和 system.exit(1)

    本文链接:https://www.haomeiwen.com/subject/idhrqltx.html