while((s = br.readLine()) != null){
          bw.write(getMobileFrom(s));
          bw.newLine();
         }上面是我写的一个代码的片段,现在的问题是,在不修改这代码的情况,怎样在这循环里添加一条语句,这样可以让这循环语句,比如每隔一分钟再循环读取下一个字符串,意思就是每个循环之间的执行时间要间隔一分钟,各位大哥支个招吧

解决方案 »

  1.   

    while((s = br.readLine()) != null){
      bw.write(getMobileFrom(s));
      bw.newLine();
      Thread.sleep(1000*60);
      }
    不过其实用java的定时器Timer获取更优雅一点,上面是让线程休眠60秒,效果一样
      

  2.   

    严格地说用Timer更精确些,因为用Thread.sleep是在readLine、write、newLine三步之后再休眠。所以执行间隙是略高于60s的。但是这点误差通常可以忽略不计。再加上用Timer的话就得修改LZ的程序结构,所以在下也是推荐用Thread.sleep。由于楼上已经写了Thread.sleep改程序的方法了,在下就献丑写下用Timer写的方法吧。public class Test5 {
    public static void main(String[] args) {
    java.util.Timer t = new java.util.Timer(); t.schedule(new Task(), 0, 60000);
    }
    }class Task extends java.util.TimerTask {
            ...... @Override
    public void run() {
                    String s;
                    if((s = br.readLine()) != null){
                            bw.write(getMobileFrom(s));
                            bw.newLine();
                    } else {
                            this.cancel();
                    }
    }
    }
      

  3.   

    用线程,但记得Thread.sleep();可能会抛出一个异常interruptedException
      

  4.   

    static void sleep(long millis)
              Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
      

  5.   

    顶一下
    Timer 有计时器 建议用这个
      

  6.   

    一般就是用线程了。不过这个FOR循环为什么需要暂停?