I want to print to the console every second. So far, I've been able to think of two ways to do this.
long start_time = System.currentTimeMillis();
while(true){
if ((System.currentTimeMillis() - start_time) >= 1000) {
System.out.println("One second passed");
start_time = System.currentTimeMillis();
}
}
And this
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("One second passed");
}
Is any method safer or more reliable or more efficient than the other? or maybe there are use cases for each? Thanks
CodePudding user response:
This is not as simple as it seems.
The problem with your solutions are that the first is very inefficient, and the second is liable to drift because sleep(1000)
does not guarantee to sleep for exactly 1 second. (The javadoc says that sleep(1000)
sleeps for at least one second.)
One possibility is to use ScheduledExecutorService.scheduleWithFixedDelay
and compute the delay each time by looking at the difference between the millisecond clock and your start time (or end time). That will keep your messages in sync with real time (more or less).
Or maybe you can simplify that using scheduleAtFixedRate
, because it looks like ScheduledThreadPoolExecutor
will take care of the clock syncing problem.
Another possibility is to look for a 3rd-party library that implements a "cron-like" scheduler in Java.