Java - thread.sleep的替代品 [英] Java - alternative to thread.sleep
本文介绍了Java - thread.sleep的替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要暂停一个while循环一段特定的毫秒数。我尝试过使用Thread.sleep(持续时间),但它不准确,尤其是在循环方案中。毫秒精度在我的程序中很重要。
I have a requirement to pause a while loop for a specific number of milliseconds. I have tried using Thread.sleep(duration) but it is not accurate, especially in a looping scenario. Millisecond accuracy is important in my program.
这是我不想回去检查条件的算法,直到 expectedElapsedTime
已经过去了。
Here is the algorithm where I don't want to go back to check for condition until expectedElapsedTime
has passed by.
while (condition) {
time = System.currentTimeMillis();
//do something
if (elapsedTime(time) < expectedElapsedTime) ) {
pause the loop // NEED SUBSTITUTE FOR Thread.sleep()
}
// Alternative that I have tried but not giving good results is
while ((elapsedTime(time) < expectedElapsedTime)) {
//do nothing
}
}
long elapsedTime(long time) {
long diff = System.currentTimeMillis() - time;
return diff;
}
推荐答案
尝试 ScheduledThreadPoolExecutor 。它应该提供更可靠的计时结果。
Try a ScheduledThreadPoolExecutor. It's supposed to give more reliable timing results.
这篇关于Java - thread.sleep的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文