简体   繁体   中英

Infinite for loop

This code works fine:

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.");
    }
}

But then, I tried rewriting it into a for loop , and it gets stuck in an infinite 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");
}

Your second example is not an infinite loop, just wait 1 minute.

long endTime = startTime + 60000;

set the endTime to 60000 milliseconds in the future, that means 60 seconds, means 1 minute.

The standard output is just printing extremely fast.

Put a Thread.sleep(1000L) in the loop and you will see 61 statements being printed before it ends.

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

This worked for me:

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

The only difference between mine an yours is where I put this: (yours is outside the main method)

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

You should also be aware it take just microseconds to run through the loop so you're getting a huge output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM