1

我想知道这门课的问题在哪里,我正在做一门课,每隔 n 秒就会做一些事情,但它似乎只做 1 次。这是课

import java.util.Timer;
import java.util.TimerTask;

public class Updater {
    private Timer timer;
    public Updater(int seconds){
        timer = new Timer();
        timer.schedule(new UpdaterTask(), seconds*1000);
    }
    class UpdaterTask extends TimerTask {
        public void run() {
            System.out.println(Math.random());
            timer.cancel();
        }
    }
}

这是测试

public class TestUpdater {
    public static void main(String[] args){
        new Updater(1);
    }
}

我认为这个测试必须每秒给我一个随机数,但在第一秒之后进程终止。抱歉英语不好,感谢任何建议

4

3 回答 3

0

当您的main()线程终止时,应用程序也会终止。

只需Thread.sleep(10000)在代码末尾添加即可。然后它将工作 10 秒。

有关如何使用取消方法的信息,请参阅此答案。我想你不想在那里使用它。

更改调度类型,使用

timer.scheduleAtFixedRate(new UpdaterTask(), 0, seconds*1000);

于 2013-05-24T12:10:35.037 回答
0
  1. schedule(task, delay)只执行一次任务。schedule(task, delay, period)以固定延迟重复执行任务。

    timer.schedule(new UpdaterTask(), 0, seconds * 1000)
    
  2. 消除cancel()

    // timer.cancel();
    
于 2013-05-24T12:13:39.680 回答
0

你需要注释掉,timer.cancel()调用。这使计时器本身在其计时器任务第一次执行后停止。

然后对于重复执行,您应该调用scheduleAtFixedRate方法,使用delay == 0, 立即启动任务,并且period == x seconds, 每隔x seconds.

class Updater {
    private Timer timer;
    public Updater(int seconds){
        timer = new Timer();
        timer.scheduleAtFixedRate(new UpdaterTask(), 0, seconds*1000); // use scheduleAtFixedRate method
    }
    class UpdaterTask extends TimerTask {
        public void run() {
            System.out.println(Math.random());
            //timer.cancel(); --> comment this line
        }
    }
}
于 2013-05-24T12:15:19.433 回答