问题是这样的:
我想实现一个判断是否超时的功能,在主类中输入字符串,如果字符串没有在规定的时间内输入,则发出一个超时异常,否则“立即”退出程序。程序的思路是这样的://主类
class Main{
  1.启动计时器(开始计时)
  2.输入字符串
   3.关闭计时器(有条件判断)
   4.退出程序
}//计时器类
class Timer{
  
}
结果是我一输入字符串,不管是否超时都会发生
“java.lang.IllegalStateException: Timer already cancelled.”错误
还请高手指点迷津!!!先谢谢了(不够再加分)

解决方案 »

  1.   

    Timer already cancelled...在判断之前就已经被停止了!?
      

  2.   

    其实程序一启动就开始计时,也就是说,不管是否超时,都要用到Timer.Cancel()
      

  3.   

    Thread x,y;
    public void getInput() {
      x = new Thread() { new Runnable() {
        public void run() {
            .... // get input
        if(y.xxdsdfsf()) // kill y;
        }
      };
      y= new Thread() { new Runnable() {
        public void run() {
           try{Thread.sleep(second * 1000) }catch(Exception e){}
            if(x.asfdafdasdfad() )
              //kill x    }
      };
      x.start();
      y.start();
      ...
    }
      

  4.   

    因为程序一启动就开始计时,所以不管是否超时,都需调用Timer.cancel()方法来关闭计时器,也就是说我在计时器类里加了cancel()方法,再3.关闭计时器(有条件判断)中也加了cancel()方法,目的就是想当输入完字符串键回车时,程序能“立即”退出;
      如果不加cancel()方法刚还要等计时器也执行完毕后才可使程序退出,这样就相当于程序还要延迟一段时间才可离开。
      

  5.   

    to:helpall() 
    这样写可以起到计时器的功能吗!?
      

  6.   

    Thread x, y;
      public void getInputTimer() {
        final int second = 10;
        (x = new Thread(new Runnable() {
          public void run() {
            try {
              int ch;
              while ( (ch = System.in.read()) != 10) {
                System.out.println( ch+"   "+(char) ch);
              }
            }
            catch (Exception e) {
              e.printStackTrace();
            }
            if (y.isAlive()) {
              y.interrupt();
              System.out.println("Killed Timer thread.");
            }
            System.out.println("Keyboard thread ends.");
          }
        })).start();
        (y = new Thread(new Runnable() {
          public void run() {
            try { Thread.sleep(second * 1000); } catch (Exception e) {}
            if (x.isAlive()) {
              x.interrupt();
              System.out.println("Killed keyboard thread.");
            }
            System.out.println("Timer thread ends.");
          }
        }
        )).start();
      System.out.print("End");
    }