gpt4 book ai didi

Java - 替代 thread.sleep

转载 作者:IT老高 更新时间:2023-10-28 20:52:26 24 4
gpt4 key购买 nike

我需要将 while 循环暂停特定的毫秒数。我曾尝试使用 Thread.sleep(duration) 但它不准确,尤其是在循环场景中。毫秒精度在我的程序中很重要。

这是在 expectedElapsedTime 过去之前我不想回去检查条件的算法。

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 .它应该提供更可靠的计时结果。

关于Java - 替代 thread.sleep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9143719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com