When a Java TimerTask is scheduled in a Timer, is it already “executing”?

前端 未结 2 865
既然无缘
既然无缘 2021-02-08 02:08

I would like to clarify something about TimerTask. When you have the code below:

timer.schedule(task, 60000);

where the task is scheduled to ru

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 02:55

    I don't know why your code returns false.

    The following code prints true.

    import java.util.Timer;
    import java.util.TimerTask;
    
    
    public class Test {
        public static void main(String[] args) {
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
    
                @Override
                public void run() {
                    System.out.println("hi");
                }
    
            };
            timer.schedule(task, 60000);
            System.out.println(task.cancel());
        }
    }
    

    If the last println is commented, the program prints hi.

提交回复
热议问题