Java计时器每秒100次

时间:2015-01-21 12:18:14

标签: java time timer

我想每秒运行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是否等于输出时间。它要么慢,要么快。例如输出:

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)

EDIT2: 已更改为timer.scheduleAtFixedRate,现在工作正常。 THnx @GeorgeG

4 个答案:

答案 0 :(得分:3)

您可以使用Timer.scheduleAtFixedRate并每0.01秒运行一次。

答案 1 :(得分:2)

您可以使用Thread.sleep(10L)。这将睡眠线程10ms。所以它每秒执行100次

答案 2 :(得分:1)

您可以调用Thread.sleep()以降低执行速度。

答案 3 :(得分:0)

试试这个:

int i = 100;

while (i-- > 0) {
    myMethod();
    try { Thread.sleep(10); } catch (Exception e) {}
}