【问题标题】:Infinite for loop无限循环
【发布时间】:2013-09-05 19:46:53
【问题描述】:

这段代码运行良好:

public class Main {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        long endTime = startTime + 60000;
        long index = 0;

        while (true) {
            double x = Math.sqrt(index);
            long now = System.currentTimeMillis();
            if (now > endTime) {
                break;
            }

            index++;
        }
        System.out.println(index + " loops in one minute.");
    }
}

然后,我尝试将其重写为for loop,但它陷入了无限循环。

public class Main {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        long endTime = startTime + 60000;

        int i = 0;
        for (long now = 0; now < endTime; i++) {
            Math.sqrt(i);
            now = System.currentTimeMillis();
            System.out.println("now" + now);
            System.out.println("end" + endTime);
        }
    }

    System.out.println(i+"calculations done in one minute");
}

【问题讨论】:

  • 您正在重置循环内now 的值。因此,now 将始终小于 endTime
  • 你的第二种方法是如何编译的? System.out 不属于任何方法。
  • 不是死循环,等1分钟就行了。
  • @Jbird: now 设置为 System.currentTimeMillis(),这就是它应该工作的原因。
  • 输出是什么?应该有很多。也许是写输出导致它需要超过一分钟的时间?

标签: java for-loop while-loop infinite-loop


【解决方案1】:

这对我有用:

public class Main {

public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    long endTime = startTime + 60000;

    int i = 0;
    for (long now = 0; now < endTime; i++) {
        Math.sqrt(i);
        now = System.currentTimeMillis();
        System.out.println("now" + now);
        System.out.println("end" + endTime);
    }

    System.out.println(i+"calculations done in one minute");
}
}

我和你的唯一区别是我把这个放在哪里:(你的在 main 方法之外)

System.out.println(i+"calculations done in one minute");

您还应该知道,循环运行只需几微秒,因此您会获得巨大的输出。

【讨论】:

    【解决方案2】:

    您的第二个示例不是无限循环,请等待 1 分钟。

    long endTime = startTime + 60000;
    

    将endTime设置为未来60000毫秒,即60秒,即1分钟。

    标准输出的打印速度非常快。

    Thread.sleep(1000L) 放入循环中,您将看到在结束之前打印了 61 条语句。

    long endTime = 1378140843604L; // for example
    for (long now = 0; now < endTime; i++) {
        now = System.currentTimeMillis(); // will be 1378140783604, 1378140784604, 1378140785604 and so on
        System.out.println("now" + now); 
        System.out.println("end" + endTime);
        Thread.sleep(1000L);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2018-10-11
      相关资源
      最近更新 更多