简体   繁体   English

如何在Java中使线程等待1ms?

[英]How can I make thread waits for 1ms in Java?

If I have a certain line, that I want any thread to wait for 1ms before execute it. 如果我有某一行,我希望任何线程在执行之前等待1ms。 How can I achieve this please. 我怎么能实现这个目标。 I'm using the following lines before the line that I wanted but not sure if this is the right thing: 我在我想要的行之前使用以下行但不确定这是否正确:

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

Very few systems have a resolution of 1ms in the System.currentTimeMillis() call. 很少有系统在System.currentTimeMillis()调用中具有1ms的分辨率。 If you want to wait until it changes then that is what you should do. 如果你想等到它发生变化,那就是你应该做的。

long start = System.currentTimeMillis();
while ( System.currentTimeMillis() == start ) {
  Thread.sleep(1);
}

or perhaps a little better: 或者好一点:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM