JAVA:为什么以下无限循环终止而没有任何错误/异常 [英] JAVA : Why does the following infinite loop terminate without any error / exception

查看:90
本文介绍了JAVA:为什么以下无限循环终止而没有任何错误/异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我惊讶的是,当我发现运行时该段代码被终止而没有任何错误/异常时,我却在日食中弄乱了

I was messing around with stuff in my eclipse when, to my surprise, I found that this piece of code when run gets terminated without any error / exception

public class Test {
    public static void main(String[] args) {
        for(int i = 2; i > 0; i++){
            int c = 0;
        }
    }
}

在他的代码不断执行的同时

while his piece of code keeps on executing

public class Test {
    public static void main(String[] args) {
        for(int i = 2; i > 0; i++){
            int c = 0;
            System.out.println(c);
        }
    }
}

即使这两个都应该是永远运行的无限循环.为什么第一个代码片段终止会丢失我什么?

Even though both ought to be infinite loops running for ever. Is there something I'm missing as to why the first code snippet is terminated?

推荐答案

首先,两个代码段都不是无限循环,因为i一旦通过Integer.MAX_VALUE就会变为负数.他们只需要很长时间就可以运行. 第一个代码段运行的时间要少得多,因为它不需要打印任何内容,并且编译器可能很聪明,可以优化代码并消除循环,因为它什么都不做.

First of all, both snippets are not infinite loops, since i will become negative once it passes Integer.MAX_VALUE. They just take a long time to run. The first snippet takes much less time to run, since it doesn't have to print anything, and it's possible the compiler is smart enough to just optimize the code and eliminate the loop, since it does nothing.

测试您的第一个代码段,在循环之前和之后添加System.out.println (System.currentTimeMillis ());,我得到了:

Testing your first snippet, adding System.out.println (System.currentTimeMillis ()); before and after the loop, I got :

1486539220248
1486539221124

即它在不到1秒的时间内运行.

i.e. it ran in less than 1 second.

略微改变循环:

System.out.println (System.currentTimeMillis ());
for(int i = 2; i > 0; i++){
    int c = 0;
    if (i==Integer.MAX_VALUE)
        System.out.println (i);
}
System.out.println (System.currentTimeMillis ());

我知道了

1486539319309
2147483647
1486539319344

如您所见,i0递增到Integer.MAX_VALUE不到1秒,然后溢出,这时循环终止.

As you can see, it takes i less than 1 second to increment from 0 to Integer.MAX_VALUE, and then overflow, at which point the loop terminates.

添加到循环中的打印越多,终止所花费的时间就越多.例如:

The more prints you add to the loop, the more time it will take to terminate. For example :

System.out.println (System.currentTimeMillis ());
for(int i = 2; i > 0; i++){
    int c = 0;
    if (i % 100000000 == 0)
        System.out.println (i);
}
System.out.println (System.currentTimeMillis ());

输出:

1486539560318
100000000
200000000
300000000
400000000
500000000
600000000
700000000
800000000
900000000
1000000000
1100000000
1200000000
1300000000
1400000000
1500000000
1600000000
1700000000
1800000000
1900000000
2000000000
2100000000
1486539563232

现在花了3秒钟.

这篇关于JAVA:为什么以下无限循环终止而没有任何错误/异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆