gpt4 book ai didi

java - 简单时钟应用程序的准确 Thread.sleep?

转载 作者:行者123 更新时间:2023-11-30 04:11:35 25 4
gpt4 key购买 nike

我有一个简单的时钟线程,每秒更新一次时间。为了实现这一点,我使用 Thread.sleep(1000) 每隔 1 秒调用一次工作类,但是,时钟的运行速度似乎比我的计算机时钟稍快。有没有办法标准化 sleep 时钟,使其在一秒钟内准确醒来,与我的电脑时钟相同?

最佳答案

根据JavaDoc:,这应该是可以预料到的。

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

您可以做的就是减少 sleep 时间,例如 400 毫秒,然后检查时间是否已更改。

或者,您可以使用Timer每秒触发一次事件并更新您的时间。

编辑:根据您的评论,您可以这样做:

long initTime = System.getTimeinMillis();
while(true)
{
Thread.sleep(200);
if((System.getTimeInMillis() - initTime) >= 1000)
{
initTime = System.getTimeInMillis();
//Update your timer.
}
}

关于java - 简单时钟应用程序的准确 Thread.sleep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com