2012-08-02 85 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