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

Zai*_*ris 5 java debugging jvm loops 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);

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

在java for循环中是否有一些优化?

笔记:

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

Jon*_*eet 2

我相信这是 Java 6 某些版本中对非常紧密循环的 JIT 处理中的一个错误。它可能bug 6196102或 bug 6357124

更新到 Java 7 应该可以,尽管我知道这对您的情况没有多大帮助。您可能会发现,在循环中添加“看起来不是无操作,但执行了您不关心的操作”方法调用也可以解决问题。例如,您可以对 的所有值求和i,然后将其打印到某个诊断日志以供忽略。