System.exit(0)与System.exit(x)

System.exit(0)是将你的整个虚拟机里的内容都停掉了
System.exit(0)是正常退出程序,而System.exit(1)或者说非0表示非正常退出程序
正常退出和非正常退出具体是什么个情况?

正常退出 是指如果当前程序还有在执行的任务,则等待所有任务执行完成以后再退出;非正常退出 是只要时间到了,立刻停止程序运行,不管是否还有任务在执行。这个效果就类似于 linux 里面的 kill -9 和 kill -15 。

相同点:后续代码都不会再执行
栗子1:
public class TestExit {
public static void main(String[] args) {
try {
System.out.println("exit 0");
System.exit(0);
System.out.println("exit normally");
System.exit(1);
System.out.println("exit abnormally");
} finally {
System.out.println("exit");
}
}
}

相同点:hook都会执行
栗子1:
执行结果:exit 0
public class TestExit {
public static void main(String[] args) {
try {
System.out.println("exit 0");
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hook exit");
}
}));
System.exit(0);
System.out.println("exit normally");
} finally {
System.out.println("exit");
}
}
}
执行结果:
exit 0
hook exit
栗子2:
public class TestExit {
public static void main(String[] args) {
try {
System.out.println("exit 0");
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hook exit");
}
}));
//System.exit(0);
//System.out.println("exit normally");
System.exit(1);
System.out.println("exit abnormally");
} finally {
System.out.println("exit");
}
}
}
执行结果同上

源码分析
public final class 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);
}
}
从方法的注释中可以看出此方法是结束当前正在运行的Java虚拟机,这个status表示退出的状态码,非零表示异常终止。注意:不管status为何值程序都会退出,和return 相比有不同的是:return是回到上一层,而System.exit(status)是回到最上层。即程序立刻中止

不同点1:
返回值不一样
Process finished with exit code 1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容