将Java虚拟机与System.nanoTime同步 [英] Synchronize Java Virtual Machine with System.nanoTime

查看:209
本文介绍了将Java虚拟机与System.nanoTime同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将java虚拟机
与System.nanoTime()同步是否有意义?

Does it make sense to synchronize java virtual machines with System.nanoTime () ?

我的意思是:


  • 调用System.nanoTime()并将结果放入t1

  • A发送数据包给B

  • 当在B上收到来自A的数据包时,B调用System.nanoTime()并在A,A呼叫上收到来自B的数据包时将结果发送到A

  • System.nanoTime()并将结果放入t3,将收到的时间从B中包含在t2中

  • timeshift =(t3 - t1)/ 2 - t2

  • A call System.nanoTime () and puts the results in t1
  • A send a packet to B
  • when the packet from A is received on B, B call System.nanoTime() and sends the result to A
  • when the packet from B is received on A, A call System.nanoTime () and puts the results in t3, puts the time received in the packet from B in t2
  • timeshift = (t3 - t1) / 2 - t2

使用System.nanoTime这样做是否正确?

is it correct to use System.nanoTime to do that ?

谢谢!

推荐答案


使用System.nanoTime执行此操作是否正确?

is it correct to use System.nanoTime to do that ?

不。 System.nanoTime() 仅用于测量单个JVM中的差异时间,而不是跨多个JVM的绝对时间。

No. System.nanoTime() is only useful for measuring time differences within a single JVM, not absolute time across multiple JVMs.


此方法只能用于测量经过的时间,与系统或挂钟时间的任何其他概念无关。返回的值表示纳秒,因为某些固定但任意的原始时间(可能在将来,因此值可能为负)。在Java虚拟机的实例中,此方法的所有调用都使用相同的原点;其他虚拟机实例可能使用不同的来源。

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

要解决这个问题,通常你会使用 System.currentTimeMillis(),但这仍然受到两台计算机的OS时钟的限制。 使用NTP在计算机之间同步时间。

To solve that problem, in general you'd use System.currentTimeMillis(), but that's still limited by the OS clocks of the two computers. Use NTP to synchronize time across computers.

请参阅使用Java的服务器和Internet之间的时间同步

这篇关于将Java虚拟机与System.nanoTime同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆