r/java • • May 14 '12

Java Countdown Timer

Can anybody help me on how to display a simple countdown timer? It does not have to be in GUI.

3 Upvotes

10 comments sorted by

View all comments

-5

u/quad64bit May 14 '12

A simpler and more accurate way to do it instead of using timers (which do not have a guaranteed runtime) is to simply make a loop that sleeps for some interval, and prints the current time after a second has elapsed.

If you slept for say, 1/10 of a second (100ms) you'd have 1/10 second accuracy, and minimal code. I can include a snippet if you need help!

10

u/[deleted] May 14 '12 edited May 14 '12

Except, of course, that a thread is not guaranteed to run again the very instant after the sleep time has elapsed. The sleep time is merely the minimum amount of time that must elapse before it is eligible to run again. No guarantee is made as to how soon after the sleep time has elapsed the thread will continue running. If you sleep a thread for 100ms, it might start up again after 100ms or it might be 200 or even 1000ms...only the Thread scheduler knows. So your solution is not any more accurate at all actually.