文章目录
原作者解释得很清晰明,因此摘抄于此。
关于System.exit(status)
System.exit(status)源码说明如下:
System.java
/**
* Terminates the currently running Java Virtual Machine. The
* argument serves as a status code; by convention, a nonzero status
* code indicates abnormal termination.
*/
public static void exit(int status) {
Runtime.getRuntime().exit(status);
}
Runtime.java
/**
* Terminates the currently running Java virtual machine by initiating its
* shutdown sequence. This method never returns normally. The argument
* serves as a status code; by convention, a nonzero status code indicates
* abnormal termination.
* /
public void exit(int status) {
// Make sure we don't try this several times
synchronized(this) {
if (!shuttingDown) {
shuttingDown = true;
Thread[] hooks;
synchronized (shutdownHooks) {
// create a copy of the hooks
hooks = new Thread[shutdownHooks.size()];
shutdownHooks.toArray(hooks);
}
// Start all shutdown hooks concurrently
for (Thread hook : hooks) {
hook.start();
}
// Wait for all shutdown hooks to finish
for (Thread hook : hooks) {
try {
hook.join();
} catch (InterruptedException ex) {
// Ignore, since we are at VM shutdown.
}
}
// Ensure finalization on exit, if requested
if (finalizeOnExit) {
runFinalization();
}
// Get out of here finally...
nativeExit(status);
}
}
}
注释中说的很清楚,这个方法是用来结束当前正在运行中的java虚拟机。
如何status是非零参数,那么表示是非正常退出。
- System.exit(0)是将你的整个虚拟机里的内容都停掉了 ,而dispose()只是关闭这个窗口,但是并没有停止整个application exit() 。无论如何,内存都释放了!也就是说连JVM都关闭了,内存里根本不可能还有什么东西
- System.exit(0)是正常退出程序,而System.exit(1)或者说非0表示非正常退出程序
- System.exit(status)不管status为何值都会退出程序。和return 相比有以下不同点:return是回到上一层,而System.exit(status)是回到最上层
举例说明
在一个if-else判断中,如果我们程序是按照我们预想的执行,到最后我们需要停止程序,那么我们使用System.exit(0)。而System.exit(1)一般放在catch块中,当捕获到异常,需要停止程序,我们使用System.exit(1)。这个status=1是用来表示这个程序是非正常退出。
![[摘]Java反射的方法反射的基本操作](https://www.biumall.com/wp-content/themes/BiuX/assets/images/random/0.webp)