因为渲染是微不足道的,所以我发现您的示例的这种变化非常平滑。渲染时间远低于半毫秒,所以12毫秒期间(〜83赫兹)是 足够
的时间来完成一帧,典型地以小于10%的一种核心的。随着渲染时间的增加,计时器线程变得饱和,并且事件合并。由于渲染与垃圾收集和外部处理需求竞争,因此在单个内核上放大了效果。Java不是实时系统,并且并非所有调度程序都是相同的。
您一定会按照此处的建议分析实际的代码,以查看与性能波动之间的任何关联。一种替代方法是延长周期(降低频率)以满足您的渲染截止日期,并使用更大的增量
moveImage()来获得相同的速度。
import java.awt.Color;import java.awt.EventQueue;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Jframe;import javax.swing.JPanel;import javax.swing.Timer;public class Main extends Jframe { private static final int W = 800; private static final int H = 400; public Main() { super("Jframe"); this.add(new ImagePanel()); setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); this.pack(); setSize(W, H); this.setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new Main(); } }); } class ImagePanel extends JPanel { Timer movementTimer; int x, y; public ImagePanel() { x = 0; y = 0; movementTimer = new Timer(12, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { moveImage(); repaint(); } }); movementTimer.start(); } public void moveImage() { x++; y++; if (x > W) { x = 0; } if (y > H) { y = 0; } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); long start = System.nanoTime(); g.setColor(Color.RED); g.fillRect(0, 0, W, H); g.setColor(Color.BLUE); g.fillRect(x, y, 50, 50); double delta = (System.nanoTime() - start) / 1000000d; g.drawString(String.format("%1$5.3f", delta), 5, 15); } }}


