0

如果我有某一行,我希望任何线程在执行它之前等待 1 毫秒。请问我怎样才能做到这一点。我在我想要的行之前使用以下行,但不确定这是否正确:

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());
}
4

1 回答 1

2

很少有系统在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;
}
于 2012-07-06T10:09:03.733 回答