From a "how can I make this work within the selected methodology (using currentTimeMillis) which has some value for the sake of learning so that the next time I need to do something similar and it's the right way I won't be stuck, even though it's not the best way this time" perspective:
long start = System.currentTimeMillis();
long now = System.currentTimeMillis();
while (now - start > 1000) // While the difference between the two times is less than a second
{
now = System.currentTimeMillis();
}
You could even try to correct for the error (now-start-1000
could be greater than 1 after all, that would be lost time) and calculate any excess time. You would then take that excess and subtract it from the 1000 in the loop's conditional so that the next time around you'd wait just a little less time to make up for the excess from the last time. Also, the System.out.println()
takes time, therefore you'd want to set start before the System.out.println
in order to be a little bit more accurate.
Now, hopefully I've pointed out enough of the pitfalls to demonstrate why this is a bad idea for any important timekeeping. The simplest way to be more accurate involves the use of Timer which uses threads allowing for the printing and other overhead to be separated out from the timekeeping. However, it simply uses a less interesting but more simple explanation for the above which is Object.wait() which "does not offer real-time guarantees".