簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM