关于 java 定时器

About java Timer

我正在 java 中使用 Timer 进行一些测试。

我的程序启动一个Timer,然后等待2秒,取消Timer并打印出j变量。

然而,即使我取消了它,计时器仍然运行。谢谢

public static Timer time;
public static int j=0;

    public static void main(String[] args)
    {
        try {
            testrun();
            Thread.sleep(2000);
            time.cancel();
            System.out.println("timer stop");

            System.out.println(j);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void testrun()
    {
        time = new Timer();
        time.schedule(new TimerTask() {
              @Override
              public void run() {
                  for(int i = 0;i<100;i++){
                  System.out.println(i);
                  j++;
                  }

                  System.out.println("End timer");
              }
            }, 1000, 1000);
    }

因为 cancel 只会中止计时器 - 如果任务已经开始,它将 运行 完成。

如果您想中止任务,您需要跟踪它并调用它的 interrupt 方法。

public static Timer time = new Timer();
public static Thread runningThread = null;
public static int j = 0;

public static void main(String[] args) {
    try {
        testrun();
        Thread.sleep(2000);
        time.cancel();
        System.out.println("timer stop");
        if (runningThread != null) {
            // Interrupt the thread.
            runningThread.interrupt();
        }
        System.out.println(j);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void testrun() {
    time.schedule(new TimerTask() {
        @Override
        public void run() {
            // Catch the thread that is running my task.
            runningThread = Thread.currentThread();
            for (int i = 0; i < 100; i++) {
                System.out.println(i);
                j++;
            }

            System.out.println("End timer");
        }
    }, 1000, 1000);
}

调用 Timer.cancel() 将停止执行任何进一步计划但未执行的任务,但不会中断 运行 任务。

参见 Javadoc for Timer.cancel()(强调我的):

Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists).