Java - thread.sleep 的替代
2022-09-01 20:50:47
我需要暂停一个 while 循环特定的毫秒数。我尝试过使用Thread.sleep(持续时间),但它不准确,特别是在循环场景中。毫秒级精度在我的程序中很重要。
这是一个算法,我不想回去检查条件,直到过去。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;
}