Keeping track of time in Java [duplicate]
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");
}
精彩评论