睡觉的时间

时间:2016-02-09 11:40:22

标签: java sleep timertask

我想将TimerTask用于Sleep,但我无法运行此代码 第一次调用run函数,然后无限等待。我的代码有什么问题吗?

import java.util.Timer;
import java.util.TimerTask;

public class TimeExecutor {

     class LocalSleep extends TimerTask {
        private int noOfSeconds;
        private int count = 0;
        private Timer timer;

        public LocalSleep(int noOfSeconds, Timer timer) {
            this.noOfSeconds = noOfSeconds;
            this.timer = timer;
        }

        void sleeeep() {
            if (count < noOfSeconds) {
                System.out.println("Count: " + count);
                count++;
            } else
                timer.cancel();
        }

        @Override
        public void run() {
            sleeeep();
        }
    }

    public static void main(String args[]) {
        Timer timer = new Timer();
        TimeExecutor t = new TimeExecutor();
        timer.schedule(t.new LocalSleep(5, timer), 1000);
    }
}

1 个答案:

答案 0 :(得分:1)

更换后的工作

timer.schedule(t.new LocalSleep(5, timer), 1000);

使用:

timer.schedule(t.new LocalSleep(5, timer), 0, 1000);