今天像往常一样在debug跟踪的时候忽然控制台出现:
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
解决方法:
在程序main()函数中添加:System.exit(0);
将解决这个问题。
然后查了一下JDK源码。
public final class System {
}
System是一个final类。
/**
* 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) {
<span style="font-size:18px;"> Runtime.getRuntime().exit(status);</span>
}
* 该方法将终止当前正在运行的 Java 虚拟机。该方法的参数作为一个状态码(退出状态);一般来说,非零状态(Status的值不是0的时候)代码指示异常终止。(当status为不是0的参数的时候表示异常退出)。
即:
System.exit(0)是正常退出程序,而System.exit(1)或者不是0表示非正常退出程.
和return 相比有以下不同点: return是回到上一层,而System.exit(status)是回到最上层。
再仔细看我们能发现System.exit()实际上调用了:
具体如下:
<span style="font-size: 14px;">/**
* Every Java application has a single instance of class
* <code>Runtime</code> that allows the application to interface with
* the environment in which the application is running. The current
* runtime can be obtained from the <code>getRuntime</code> method.
* <p>
* An application cannot create its own instance of this class.
*
* @author unascribed
* @see java.lang.Runtime#getRuntime()
* @since JDK1.0
*/
public class Runtime {
</span><span style="font-size:24px;"> private static Runtime currentRuntime = new Runtime();</span><span style="font-size: 14px;">
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
</span><span style="font-size:24px;"> return currentRuntime;</span><span style="font-size: 14px;">
}</span>
Runtime类封装了运行时的环境。每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。
一般不能实例化一个Runtime对象,应用程序也不能创建自己的 Runtime 类实例,但可以通过 getRuntime 方法获取当前Runtime运行时对象的引用。
一旦得到了一个当前的Runtime对象的引用,就可以调用Runtime对象的方法去控制Java虚拟机的状态和行为(访问JVM信息)。