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

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退出方法,那我们的执行结果会发生怎么样的改变?




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值