java 循环时间间隔时间,Java循环持续一段时间

博客讨论了Java中如何实现在不使用System.currentTimeMillis()的情况下进行定时循环。建议使用System.nanoTime()结合TimeUnit枚举来精确控制循环时间,例如执行任务两分钟。这种方法避免了Windows系统下System.currentTimeMillis()的不准确性。
摘要由CSDN通过智能技术生成

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

*/

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值