Java中System.exit(status)和Runtime.getRuntime().halt(status)区别

System.exit(status);

Runtime.getRuntime().halt(status)

这两个都表示系统退出,那么他们有什么区别呢?

针对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

针对Runtime.getRuntime().halt(status)解释如下:

Forcibly terminates the currently running Java virtual machine.  This
method never returns normally.

具体的代码测试如下:

用户自定义线程:

class UserThread implements Runnable {

	@Override
	public void run() {
		System.out.println("***************UserThread  start********");
		try {
			Thread.sleep(1 * 1000l);
			System.out.println("***************UserThread end********");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

}

 

针对System.exit(status)测试代码:

public static void main(String[] args) throws Throwable {
	for (int i = 0; i < 10; i++) {
		Thread t = new Thread(new UserThread());
		Runtime.getRuntime().addShutdownHook(t);
	}
	System.exit(1);
}

结果:

所有的线程都执行完成之后才会退出

 

针对Runtime.getRuntime().halt(status)测试如下:

public static void main(String[] args) throws Throwable {
	for (int i = 0; i < 10; i++) {
		Thread t = new Thread(new UserThread());
		Runtime.getRuntime().addShutdownHook(t);
	}
	Runtime.getRuntime().halt(1);
}

结论:

所有的线程都没有执行

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值