我有一个桌面电脑没有互联网连接或GPS接收器。我需要构建一个NTP服务器应用程序,最好是使用JAVA,而不需要使用系统时间。
我使用了以下方法。
public void run()
{
Date oDate = new Date();
time = oDate.getTime();
System.out.println("Syst Time--->"+oDateFormat.format(time));
while(true)
{
try
{
Thread.sleep(100);
time = time+100;
oDate = new Date();
if(time % 11443 == 1)
{
System.out.println("Time--->"+oDateFormat.format(time)+" Syst Time--->"+oDateFormat.format(oDate));
oDate = null;
}
}
catch (InterruptedException ex)
{
Logger.getLogger(NTPServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}我要做的是,有一个线程可以休眠100毫秒,然后我将100添加到 time 变量中,它保留了我的时间。但每次打印时,它都会与系统时间产生2-3秒的差异。基本上不准确。
还有别的办法吗?
发布于 2015-03-10 10:29:55
使用Thread.sleep(100);并不能确保每100 is精确执行一次循环。至少有两件事需要考虑:
Thread.sleep(100)的调用之间执行的代码本身需要时间来执行。Thread.sleep(100)睡不了100 it,但它至少睡了100 it。当您的程序在Thread.sleep()未定义并依赖于实现定义的方面(如VM调度程序和OS调度程序)之后真正继续运行时。在具有非确定性定时行为的环境中,时间不能被软件测量.不确定的定时行为是由调度器、缓存、多任务、多线程、硬盘等引起的。
您必须依赖系统时间,使用System.currentTimeMillis()和System.nanoTime()。
发布于 2015-03-10 10:28:18
您可以按照文档使用System.nanoTime():
这种方法只能用于测量经过的时间,而与系统或挂钟时间的任何其他概念无关。
因此,在使用系统时间时,您不会违反您的要求。然后,您基本上需要执行以下操作:
long before = System.nanoTime();
Thread.sleep(100);
long after = System.nanoTime();
time = time+((after-before)/1000000L);您的生产代码应该知道在睡眠期间可能发生在nanoTime上的溢出。
https://stackoverflow.com/questions/28961079
复制相似问题