近空的Java For-Loop行为很奇怪

时间:2013-08-04 07:10:23

标签: java debugging loops jvm nested-loops

此代码按预期打印“平均运行次数:0.99864197”

import java.util.Random;

public class A {
    public static void main(String[] args) {
        int min = -30;
        int max = 1;
        test(min, max);
    }
    static void test(int min, int max){
        int count = 0;
        Random rand = new Random(0);
        for(int j = 0; j < 2097152; j++){
            int number = min + rand.nextInt(max-min+1);
            for(int i = 0; i < number; ++i) {
                System.out.print("");
                count++;
            }
        }
        System.out.println("Average Number of Runs: " + count/65536F);

    }
}

此代码应打印相同的确切数字,但它会打印一个随机的负数。

import java.util.Random;

public class A {
    public static void main(String[] args) {
        int min = -30;
        int max = 1;
        test(min, max);
    }
    static void test(int min, int max){
        int count = 0;
        Random rand = new Random(0);
        for(int j = 0; j < 2097152; j++){
            int number = min + rand.nextInt(max-min+1);
            for(int i = 0; i < number; ++i) {
                //System.out.print("");
                count++;
            }
        }
        System.out.println("Average Number of Runs: " + count/65536F);

    }
}

java for loops中是否有一些优化?

注意:

  1. 我正在使用jdk1.6.0_45。
  2. 在正常使用中,新的Random会有更好的种子。
  3. min和max应该可以是任何数字。

2 个答案:

答案 0 :(得分:2)

我认为这是某些Java 6版本中JIT处理非常紧密循环的错误。可能bug 6196102或bug 6357124。< / p>

更新到Java 7应该可行,但我很欣赏这对您的情况没有多大帮助。您可能会发现在循环中添加“看起来不是无操作,但做一些您不关心的事情”方法调用也可以解决问题。例如,您可以将i的所有值相加,然后将其打印到某些诊断日志中以便忽略。

答案 1 :(得分:-1)

openjdk 1.7.0_25 fedora-2.3.10.4.fc19-x86_64上可以正常使用。 您应该更新Java版本,或者确保您的问题实际上与所述代码一致。

相关问题