【发布时间】:2015-03-19 23:07:24
【问题描述】:
我想每秒运行 100 次某个方法。 我得到的是这样的:
Timer timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
time+= 0.001;
System.out.println(time);
repaint();
}
});
从输出中可以清楚地看出,计时器比它应该的要快。它也对 cpu 造成影响,所以我怀疑这是正确的方法。如果我设置new Timer(1, new ActionListener() 和time+= 0.01; 那么它应该比它应该的要慢。
谁能帮我解决这个问题?如何每秒执行 100 次任务?
编辑: 改为:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
time += 0.01;
System.out.println(time);
repaint();
}
}, 1, 1);
不确定它的 netbeans 是否,但输出时间是 waaay 的。它要么慢,要么快。例如输出:
57.07999999999721
57.08999999999721
57.09999999999721
57.10999999999721
BUILD STOPPED (total time: 24 seconds)
5.699999999999923
5.709999999999923
5.7199999999999225
5.729999999999922
5.739999999999922
BUILD STOPPED (total time: 8 seconds)
编辑2:
更改为timer.scheduleAtFixedRate,现在可以正常工作了。 THnx @GeorgeG
【问题讨论】:
-
为什么不将延迟设置为 10?