2012-08-02 86 views
2

出於某種原因,我得到由函數返回一個一致的3600:Java - System.currentTimeMillis();不返回差異

private static long getCountdownLeft() { 
    long now = System.currentTimeMillis(); 
    long elapsedMillis = now - initialTime; //difference of current 'current' time 
    long millisLeft = secondsOfGame * 1000 - elapsedMillis; 
    return millisLeft/1000; 
} 

public static void Main(String[] args) { 
    System.out.println("Time is " + getCountdownLeft()); 
} 

private static int secondsOfGame = 3600; 
private static long initialTime = System.currentTimeMillis(); 

這是事件驅動的。每次我調用函數時,我都希望看到時間上的差異。我只是用main來表明我正在調用它。

+1

並且您還從靜態上下文中獲取非靜態上下文。所以這是另一個編譯問題。我明白'Main'只是爲了演示,但是在這裏嘗試使用代碼來讓那些想要幫助你的人更容易:) – 2012-08-02 04:24:52

+0

附註:'Main'?這是故意還是錯字? – 2012-08-02 04:25:09

+0

w/e主!我爲我的懶惰道歉。 – user1513909 2012-08-02 04:26:14

回答

2

這很可能是因爲elapsedMillis即將爲零。我建議使用System.nanoTime()來計算已用時間。

我不太確定你的代碼是如何工作的(正如現在所發佈的),但類似的東西可能會起作用。請注意,您需要添加您的邏輯運算,這只是一個例子:

public class TimeTest { 

    private long startTime; 

    public TimeTest(){ 
     startTime = System.nanoTime(); 
    } 

    public void computeTimeDifference(){ 
     long currentTime = System.nanoTime(); 
     long elapsedTime = currentTime - startTime; 

     System.out.println("Difference: "+elapsedTime+ "ns"); 
    } 

    public static void main(String[] args) { 
     new TimeTest().computeTimeDifference(); 
    } 
} 
+0

由於系統。當我使用它時,currentTimeMillis始終是'當前'時間。不會讓它> 0? – user1513909 2012-08-02 04:18:06

+0

您每次運行程序時都設置一個新的當前gameTime,然後立即調用getCountdownLeft(gameTime)。大約經過時間爲0. – irrelephant 2012-08-02 04:19:03

+0

同意@irrelephant。調用方法之間的時間差爲零,因此您看不到任何區別。 – Sujay 2012-08-02 04:20:05

0

您的代碼會消耗一點時間之前調用getCountdownLeft。請嘗試更新代碼:

public static void Main(String[] args) throws InterruptedException { 
    long gameTime = System.currentTimeMillis(); // pass the current time 
    Thread.currentThread().sleep(1000); // sleep one second before invoke getCountdownLeft 
    System.out.println("Time is " + getCountdownLeft(gameTime)); 
} 
+0

它實際上是一個回調,每4秒回撥一次,我認爲我會因爲某些原因省略 – user1513909 2012-08-02 04:19:15

0

嘿,我剛剛爲prev,new和elapsed變量添加了print語句。該值是

前一次1343882409054

目前1343882409054

經過時間0

時間是3600

所以你millisLeft永遠是3600。

但是,如果你嘗試使用

System.nanoTime()

的值,

一時間519222175869357

目前519222175923421

經過時間54064

時間是3545

所以,你必須要更精細這裏,並考慮使用System.nanoTime()。

+0

答案已發佈。感謝您的關注。 – user1513909 2012-08-02 05:00:21