Is there a way I can do a for loop for a certain amount of time easily? (without measuring the time ourselves using System.currentTimeMillis() ?)
I.e. I want to do something like this in Java:
int x = 0;
for( 2 minutes ) {
System.out.println(x++);
}
Thanks
解决方案
No, there isn't a built-in construct which does that.
I want to point out that you should not use System.currentTimeMillis() for performing, or delaying, a task for a specified time period. Instead use System.nanoTime(). The former method is inaccurate in Windows, while the latter method is accurate regardless of OS. You can use TimeUnit enum to easily go between time in milliseconds, or any other time unit, to time in nanoseconds.
for (long stop=System.nanoTime()+TimeUnit.SECONDS.toNanos(2);stop>System.nanoTime();) {
/*
* Hammer the JVM with junk
*/
}