1. 程式人生 > 其它 >System.nanoTime()與System.currentTimeMillis()的區別

System.nanoTime()與System.currentTimeMillis()的區別

System.nanoTime()的初始值是在本JVM例項啟動時"隨機"選擇的一個數字,隨著JVM的執行而遞增(常用來計算實時時間差),System.currentTimeMillis表示系統時間,這就導致了的它們的幾個差別:

  1. System.currentTimeMillis()表示系統時間(即UTC). System.nanoTime()無法表示當前時間,本質上它是一個隨機數字.
  2. 在同一機器上的不同JVM上,System.currentTimeMillis是相同的,System.nanoTime()是不同的.
  3. System.currentTimeMillis()系統時間敏感,System.nanoTime()系統時間不敏感.比如我們將系統時間往前調一秒,System.currentTimeMillis()相比修改前會減少1000.而System.nanoTime()不會變化.

基於System.nanoTime()系統時間不敏感的特性,它被廣泛應用在需要相對時間的場景中,如ScheduledThreadPoolExecutor,在0點0分新增一個1小時後執行的任務,那麼只有在系統執行1小時後,它才會被觸發,在此期間無論如何修改系統時間都不會影響.



轉載:https://www.jianshu.com/p/4fc9c3238164

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified
Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole
Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back