您的位置:首页 > 其它

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

2015-08-01 23:32 423 查看
1、查看java.lang.System的源代码,我们可以找到System.exit(status)这个方法的说明,代码如下:

/**
     * 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==0,表示jvm正常退出,如果status!=0非零,表示jvm非正常退出。

关于System.exit(int status)方法
System.exit(int status);//这个语句的功能是结束当前运行的Java虚拟机,其中的参数status是状态代码,当status不为0时表示这次结束Java虚拟机是一个不正常的结束,这个数是返回给操作系统的。一般在Windows底下,不正常退出状态码为-1,这里可写为System.exit(-1);

System.exit(int status)方法效果等同于于Runtime.getRuntime().exit(int n)方法


特殊案例分析:在main方法中,启动一个自定义线程,并执行system.exit方法

自定义线程代码:

package com.java.demo;

public class Calculator implements Runnable {
	private int number;

	public Calculator(int number) {

		this.number = number;
	}

	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			System.out.printf("%s: %d * %d = %d\n", Thread.currentThread().getName(), number, i, i * number);

		}

	}

}
测试方法:

package com.java.demo;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
			Calculator calculator = new Calculator(1);
			Thread thread = new Thread(calculator);
			thread.start();	   //启动自定义线程
			
			System.out.println("hello world-----1");
			
			System.exit(0);  //执行jvm 退出
			
			System.out.println("hello world------2");
			

		
		
		
		
		

	}

}


结果展示:



结果分析:我们在main方法启动一个自定义的线程,但是控制台只是输出了一个字符串“hello word--------1”.但是自定义线程中的run()方法输出的内容没有打印。以下是我根据程序执行结果,描绘的程序执行图:



留个思考问题:如果在线程销毁方法中调用jvm退出方法,那我们的执行结果会发生怎么样的改变?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: