我正在制作一个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
。这不奇怪吗?
答案 0 :(得分:3)
不,这就是应该如何运作的。 TimerTask
是一次性对象。如果要再次安排代码,请创建一个新的TimerTask
。 (参见documentation。)
如果您不喜欢每次运行都创建一个全新的对象,您可以执行类似
的操作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();
}
};
相关问题:
答案 1 :(得分:0)
简短的回答:不,不是不奇怪。
这是一个线程,它将在'取消' state,但由于语句的快速执行,线程不会被取消。所以它并不奇怪,欢迎使用101。
为什么要取消重新调用它的线程?这有什么用途?在再次调用它之前,您没有给第一个实例时间安全停止。您可能希望在重新创建它之前将timer对象设置为null。