[英]How can I make thread waits for 1ms in Java?
如果我有某一行,我希望任何线程在执行之前等待1ms。 我怎么能实现这个目标。 我在我想要的行之前使用以下行但不确定这是否正确:
try // wait for 1 millisecond to avoid duplicate file name
{
Thread.sleep(1); //wait for 1 ms
}catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
很少有系统在System.currentTimeMillis()
调用中具有1ms的分辨率。 如果你想等到它发生变化,那就是你应该做的。
long start = System.currentTimeMillis();
while ( System.currentTimeMillis() == start ) {
Thread.sleep(1);
}
或者好一点:
private static long lastMillis = 0;
static synchronized long nextMillis() throws InterruptedException {
long nextMillis;
while ((nextMillis = System.currentTimeMillis()) == lastMillis) {
Thread.sleep(1);
}
return lastMillis = nextMillis;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.