我用了一个Timer去定时处理文件夹里面的文档,但是当出现错误的时候,还是继续执行,连续报错。。如何停止?
// TODO Auto-generated method stub
Timer timer = new Timer();
timer.schedule(new Task(), 1000, 2000);// 在1秒后执行此任务,每次间隔2秒,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.
boolean OK = true;
while (OK)
{
try
{
int ch = System.in.read();
if (ch - 'c' == 0)
{
timer.cancel();// 使用这个方法退出任务
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
OK = false;
return;
}
}

解决方案 »

  1.   

       不出错才怪呢?把try...catch放在死循环外面
        try{
           while (OK){
                int ch = System.in.read();
                if (ch - 'c' == 0)
                {
                    timer.cancel();// 使用这个方法退出任务
                }
    }
        }catch (IOException e){
             e.printStackTrace();
             OK = false;//可有可无
             return;//可有可无
               
        }
     
      

  2.   

      try{
          while (OK){
                int ch = System.in.read();
                if (ch - 'c' == 0)
                {
                    timer.cancel();// 使用这个方法退出任务
                }    }catch (IOException e){
            e.printStackTrace();
            OK = false;//可有可无
            return;//可有可无
             
        } 
      

  3.   

    确实是的,当你cancle一个timer后,在启动,则会报错java.lang.IllegalStateException: Timer already cancelled.