app在使用java.util.Timer时,如果出现如下异常:
java.lang.IllegalStateException: Timer was canceled
原因可能是调用了cancel()方法,之后又调用了schedule方法,才出现的异常。因为调用cancel()方法取消定时器后,就不能再执行schedule方法。
可以通过如下方式解决此问题:
// 取消定时器后,并将其置空
timer.cancel();
timer = null;
// 在使用时,判断定时器是否为空
if (timer == null) {
timer = new timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 逻辑处理
}
}, 0, 1000);
}
本文介绍了在使用Java的util.Timer时可能出现的IllegalStateException异常及其原因。当调用了cancel()方法后再次尝试schedule任务会导致该异常。文章提供了解决方案,包括如何正确地取消和重新创建Timer。
1448

被折叠的 条评论
为什么被折叠?



