我想给我的java代码增加0.488毫秒的延迟。但是thread.sleep()和定时器函数只允许毫秒级的粒度。如何指定低于该级别的延迟量?
发布于 2012-11-27 21:17:06
从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); 发布于 2012-11-27 14:19:07
您可以使用Thread.sleep(long millis, int nanos)
请注意,您不能保证睡眠会有多精确。根据您的系统,计时器可能只精确到10ms左右。
发布于 2013-12-25 07:17:07
TimeUnit.anything.sleep()调用Thread.sleep()和Thread.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)也有同样的情况;
https://stackoverflow.com/questions/13578412
复制相似问题