【发布时间】:2012-11-14 17:31:49
【问题描述】:
我想在我的 java 代码中添加 0.488 毫秒的延迟。但是 thread.sleep() 和 Timer 函数只允许毫秒的粒度。如何指定低于该级别的延迟量?
【问题讨论】:
标签: java multithreading events timeout timedelay
我想在我的 java 代码中添加 0.488 毫秒的延迟。但是 thread.sleep() 和 Timer 函数只允许毫秒的粒度。如何指定低于该级别的延迟量?
【问题讨论】:
标签: java multithreading events timeout timedelay
从 1.5 开始你可以使用这个不错的方法java.util.concurrent.TimeUnit.sleep(long timeout):
TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(1000);
TimeUnit.MICROSECONDS.sleep(1000000);
TimeUnit.NANOSECONDS.sleep(1000000000);
【讨论】:
您可以使用Thread.sleep(long millis, int nanos)
请注意,您无法保证睡眠的精确度。根据您的系统,计时器可能只精确到 10 毫秒左右。
【讨论】:
TimeUnit.anything.sleep() 调用 Thread.sleep() 和 Thread.sleep() 四舍五入 到毫秒, 所有 sleep() 都无法使用,精度低于毫秒
Thread.sleep(long millis, int nanos) 实现:
public static void sleep(long millis, int nanos) throws java.lang.InterruptedException
{
ms = millis;
if(ms<0) {
// exception "timeout value is negative"
return;
}
ns = nanos;
if(ns>0) {
if(ns>(int) 999999) {
// exception "nanosecond timeout value out of range"
return;
}
}
else {
// exception "nanosecond timeout value out of range"
return;
}
if(ns<500000) {
if(ns!=0) {
if(ms==0) { // if zero ms and non-zero ns thread sleep 1ms
ms++;
}
}
}
else {
ms++;
}
sleep(ms);
return;
}
方法 wait(long, int); 也是同样的情况
【讨论】: