You can use break;
anytime inside of a loop to exit the loop immediately. This works for any loops in Java (e.g. for
, while
, do...while
). Example:
public void execute() {
long startTime = System.currentTimeMillis();
for (int i = 0; i <= 100000000; i++) {
long currentTime = System.currentTimeMillis();
if ((currentTime - startTime) >= 2000) {
break;
}
System.out.println(i);
}
}
That will cause the loop to exit once the time elapsed it greater than or equal to 2 seconds (Roughly).
EDIT: As @LouisWasserman commented, you can use System.nanoTime()
to be more precise and not be affected by things like leap seconds. If you use that instead, just check that the difference is greater than or equal to 2000000000
to account for the precision.