[英]What is the most efficient way to simulate a countdown in java?
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
谢谢
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.您的解决方案的问题是第一个效率非常低,第二个很容易漂移,因为
sleep(1000)
不能保证恰好睡 1 秒。 (The javadoc says that sleep(1000)
sleeps for at least one second.) (javadoc 说
sleep(1000)
至少休眠一秒钟。)
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).一种可能性是使用
ScheduledExecutorService.scheduleWithFixedDelay
并通过查看毫秒时钟与您的开始时间(或结束时间)之间的差异来计算每次延迟。 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.或者,也许您可以使用
scheduleAtFixedRate
来简化它,因为看起来ScheduledThreadPoolExecutor
会处理时钟同步问题。
Another possibility is to look for a 3rd-party library that implements a "cron-like" scheduler in Java.另一种可能性是寻找在 Java 中实现“类似 cron”的调度程序的第 3 方库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.