开发者

Keeping track of time in Java [duplicate]

This question already has answers here: 开发者_JAVA技巧 Closed 11 years ago.

Possible Duplicate:

Java Timer

How can I keep track of the remaining time in a fixed period of time in Java?

For instance, I want to display this output each second to the user:

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

And so on.


You may use Thread.sleep as a mechanism for timing the response to the user, but I wouldn't depend on it for accuracy in the countdown. Thread.sleep makes the thread active again after i.e. 1000 milliseconds, but it may take a little extra time before the thread is actually running again.

How about this:

    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");
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜