Java 摆动计时器循环变慢

Java swing Timer loop slows down

所以,我正在尝试使用 Java 中的 Swing 创建一个小游戏。我创建的游戏循环使用 javax.swing 计时器。 这个定时器(通常)每 5 毫秒调用一个循环。

Timer tm = new Timer(5, this);
tm.start();

@Override
public void actionPerformed(ActionEvent e) {
    game.tick();
    repaint();
    revalidate();
}

我的代码可能非常繁重,因为它包含相当多的 for 循环,所以我并不感到惊讶这实际上不是每 5 毫秒循环一次 运行。 相反,它以相当稳定的 160fps 流动,至少在我的电脑上是这样。当我在我兄弟的电脑(更少的 RAM)上尝试我的游戏时,它一开始 运行 以相同的 160fps,但大约 2 分钟后帧下降到稳定的 60fps。

我个人觉得帧数在同一时间间隔下降这么多并在其余时间保持稳定真的很奇怪。

如果有人遇到类似的问题并且知道是什么原因造成的,请告诉我。提前致谢。 ~克里克

您应该使用 Timer.scheduleAtFixedRate 方法而不是构造函数参数。

来自文档(强调我的):

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

正如@HovercraftFullOfEels 在评论中提到的,您应该在 Swing 事件线程上进行任何 Swing 调用。有关详细信息,请参阅 this tutorial