Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java loop for a certain duration

Tags:

java

loops

time

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

like image 593
Lydon Ch Avatar asked Mar 31 '10 04:03

Lydon Ch


People also ask

How do you make a for loop repeat a certain number of times?

You can do the same type of for loop if you want to loop over every character in a string. To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.

How do you repeat a loop on a certain number in Java?

You need a for loop. What this does is it initializes a variable called i to 0, then loops while i is less than 3, and adds 1 to i after each loop. This loop should loop 3 times ( i = 0: loop, i = 1: loop, i = 2: loop, i = 3: stop loop, since i is no longer less than 3).

How do you create a time limit in Java?

To set the time limit of a search, pass the number of milliseconds to SearchControls. setTimeLimit(). The following example sets the time limit to 1 second. // Set the search controls to limit the time to 1 second (1000 ms) SearchControls ctls = new SearchControls(); ctls.


2 Answers

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
   */
}
like image 62
Tim Bender Avatar answered Sep 21 '22 04:09

Tim Bender


I think that this is what you want:

private final Thread thisThread = Thread.current();
private final int timeToRun = 120000; // 2 minutes;

new Thread(new Runnable() {
    public void run() {
        sleep(timeToRun);
        thisThread.interrupt();
    }
}).start();

while (!Thread.interrupted()) {
    // do something interesting.
}

This avoids doing repeated syscalls to get the system clock value (which can be rather expensive) and polls the current thread's interrupted flag instead (much cheaper).

EDIT

There is actually no safe alternative to polling the clock or polling a flag. In theory, you could modify the above fragment to call the deprecated Thread.stop() method instead of Thread.interrupt().

(I do NOT recommend using Thread.stop() and friends. They are flawed, and dangerous to use. I'm just posing this as a theoretical alternative.)

EDIT 2

Just to point out that using Thread.interrupt() has the advantages over setting a shared flag:

  • Thread.interrupt() will cause certain blocking I/O and synchronization methods to unblock and throw a checked exception. Updating a shared flag won't do this.

  • Some third-party libraries also check the interrupt flag to see if they should stop what they are currently doing.

  • If your loop involves calls to other methods, etc, Thread.interrupt() means that you don't need to worry about those methods can access the flag ... if they need to.

EDIT 3

Just to add that sleep(N) is not guaranteed to wake the sleeping thread up after exactly N milliseconds. But under normal circumstances, it will be reasonably close.

like image 45
Stephen C Avatar answered Sep 22 '22 04:09

Stephen C