1

我正在制作一个 android 应用程序(QR 码阅读器),我需要每秒执行 4 次操作。为此,我决定使用 Timer 类。我发现了它的一个奇怪行为:

timer = new Timer();
timer.scheduleAtFixedRate(onTimer, 100, stn.GetStep());
timer.cancel();
timer = new Timer();
timer.scheduleAtFixedRate(onTimer, 100, stn.GetStep());

最后一行抛出一个错误 - java.lang.IllegalStateException: TimerTask is scheduled already。是不是很奇怪?

4

2 回答 2

3

不,这就是它应该如何工作的方式。ATimerTask是一次性对象。TimerTask如果您想再次安排代码,请创建一个新的。(请参阅文档。)

如果您不喜欢每次运行都创建一个全新对象的想法,您可以执行类似的操作

Runnable toRunRepeatedly = new Runnable() {
    public void run() {
        // your code goes here...
    }
};

然后做

TimerTask tt = new TimerTask() {
    public void run() {
        // Delegate to the same runnable each time.
        toRunRepeatedly.run();
    }
};

相关问题:

于 2012-07-04T11:43:50.477 回答
0

简短的回答:不,不,这并不奇怪。

它是一个线程,它将处于“取消”状态,但由于语句的快速执行,该线程还不会被取消。所以这并不奇怪,欢迎来到线程 101。

为什么要取消线程以重新调用它?这是为了什么目的?在再次调用它之前,您没有给第一个实例时间安全停止。您可能希望在重新创建计时器对象之前将其设置为 null。

于 2012-07-04T11:46:20.793 回答