Java循环持续一段时间 [英] Java loop for a certain duration

查看:167
本文介绍了Java循环持续一段时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以轻松地在一段时间内进行for循环? (不使用System.currentTimeMillis()测量时间?)

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。我想在Java中做这样的事情:

I.e. I want to do something like this in Java:

int x = 0;
for( 2 minutes )  {
   System.out.println(x++);
}

谢谢

推荐答案

不,没有内置的构造可以做到这一点。

No, there isn't a built-in construct which does that.

我想指出你不应该使用System.currentTimeMillis()用于在指定时间段内执行或延迟任务。而是使用System.nanoTime()。前一种方法在Windows中不准确,而后一种方法无论操作系统如何都是准确的。您可以使用TimeUnit枚举轻松地在毫秒之间或任何其他时间单位之间以毫秒为单位的时间。

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

这篇关于Java循环持续一段时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆