2011-03-27 97 views
1

可能重复:
Java Timer跟踪时间在Java中

我怎么可以跟踪的剩余时间的时间在Java中的固定期限?

举例来说,我想这显示输出的每个第二用户:

you have 50 seconds 
you have 49 seconds //after 1 second 
you have 48 seconds //after 2 seconds 

等。

+3

请搜索这个网站“【JAVA]计时器”,这已被问过无数次...... – Mat 2011-03-27 17:44:24

回答

4

您可以使用Thread.sleep作为计时器响应用户的机制,但我不会依赖它来确保倒计时的准确性。 Thread.sleep使线程在1000毫秒之后再次激活,但在线程再次运行之前可能需要一些额外的时间。

如何:

int remainingTime = 50; 
    long timeout = System.currentTimeMillis() + (remainingTime * 1000); 
    while (System.currentTimeMillis() < timeout) { 
     Thread.sleep(1000); 
     System.out.println("You have : " + (timeout - System.currentTimeMillis())/1000 + " seconds left"); 
    } 
+2

呃,你不混秒和毫秒在第2和5? – meriton 2011-03-27 18:09:59

+0

我做到了。修复 – sstendal 2011-03-28 12:04:33