gpt4 book ai didi

Java时钟同步

转载 作者:行者123 更新时间:2023-11-30 06:12:55 24 4
gpt4 key购买 nike

我必须在屏幕上显示来自不同地方的多个时钟,例如新德里、香港、法兰克福、华盛顿等。这些时间像任何其他真实时钟一样变化,但随着 Time-Left 变为固定的日期时间,它们在用户添加它们的不同时刻被添加到屏幕上。例如:

New Delhi       1d 4h 20 min 5s
Hong Kong 9h 2min 55s
Washington 22min 3s
...

我有一个类,它进行所有计算以获得该格式的那些时间。当这些时间显示在屏幕上时,问题就来了。我如何让他们同时更新他们的时间?所以秒内的所有变化是同时显示的。我知道理论上不会同时,但最接近它。这是我正在使用的计时器:

Timer t = new Timer();   
t.scheduleAtFixedRate(
new TimerTask()
{
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
label[id].setText(getTimeLeft(id));
}
});
}
},
0, // run first occurrence immediately
1000); // run every seconds

此外,其中一些最终会卡住。有没有人知道为什么?

最佳答案

How do I make them to update their time at the same time? So all the changes in the seconds are shown at the same time. I know it won't be theoretically at the same time, but the most close to it. This is the timer I am using:

不是为每个标签使用单独的 Timer,而是为所有标签使用单个 Timer

Timer t = new Timer();   
t.scheduleAtFixedRate(
new TimerTask()
{
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
for (int id = 0; id < label.length; id++) {
label[id].setText(getTimeLeft(id));
}
}
});
}
},
0, // run first occurrence immediately
1000); // run every seconds

这将减少您系统上的资源开销(一个计时器而不是 n 次),由于多个计时器同时触发,可能会出现事件队列垃圾邮件,并允许时间“似乎”同时更新,因为它们都是在事件队列中更新,因此它们直到下一个绘制周期才会更新,直到您退出运行 block 才会发生...

您还可以使用 Timeline,这将减少对 Platform.runLater 的需求,请参阅 How to update the label box every 2 seconds in java fx?举个例子。

关于Java时钟同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32387376/

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