Java loop for a certain duration

后端 未结 8 2138
花落未央
花落未央 2020-12-13 22:10

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 s

8条回答
  •  天命终不由人
    2020-12-13 22:22

    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
       */
    }
    

提交回复
热议问题