今天使用了thread的sleep方法,发现它有误差,而且不是延迟,而是提前结束睡眠了。
环境:Window2008 64位,使用了jdk6 32位的。while(true){
//do something
Calendar now1 = Calendar.getInstance();
logger.info("now:" +now1.get(Calendar.HOUR_OF_DAY)
+":" + now1.get(Calendar.MINUTE)
++":" + now1.get(Calendar.MILLISECOND));
Thread.sleep(180111);
Calendar now1 = Calendar.getInstance();
logger.info("now:" +now1.get(Calendar.HOUR_OF_DAY)
+":" + now1.get(Calendar.MINUTE)
++":" + now1.get(Calendar.MILLISECOND));
}运行后发现睡眠提前结束了。有点不解。
请问高手有什么意见么?
环境:Window2008 64位,使用了jdk6 32位的。while(true){
//do something
Calendar now1 = Calendar.getInstance();
logger.info("now:" +now1.get(Calendar.HOUR_OF_DAY)
+":" + now1.get(Calendar.MINUTE)
++":" + now1.get(Calendar.MILLISECOND));
Thread.sleep(180111);
Calendar now1 = Calendar.getInstance();
logger.info("now:" +now1.get(Calendar.HOUR_OF_DAY)
+":" + now1.get(Calendar.MINUTE)
++":" + now1.get(Calendar.MILLISECOND));
}运行后发现睡眠提前结束了。有点不解。
请问高手有什么意见么?
参考jdk文档:在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
jdk源码: public static native void sleep(long millis) throws InterruptedException;
比如下面这个程序段:
Long l1=System.currentTimeMillis(),l2,l3;
try{Thread.sleep(505);}
catch(Exception e){}
l2=System.currentTimeMillis();
l3=l2-l1;
PrintWriter stdout=new PrintWriter(System.out,true);
stdout.println(l3);
运行时一会儿是500,一会儿又是515.
GetSystemTimeAsFileTime API: http://msdn.microsoft.com/en-us/library/ms724397%28VS.85%29.aspx
据悉这个时间的精度在 10ms 左右。
可能是sleep的bug
不过sleep有可能不执行实际的指定时间。比如sleep(2),他可能实际上不执行sleep
http://www.javamex.com/tutorials/threads/sleep_issues.shtml
http://www.javamex.com/tutorials/threads/sleep.shtml