在下面的示例中,重复任务如何完全“错过”四次调用?

How does the recurring task “misses” four invocations completely in example below?

来自 JCIP 的摘要-

If a recurring TimerTask is scheduled to run every 10 ms and another Timer-Task takes 40 ms to run, the recurring task either (depending on whether it was scheduled at fixed rate or fixed delay) gets called four times in rapid succession after the long-running task completes, or “misses” four invocations completely.

我了解到,由于第一个任务被安排在每10ms后运行,所以在40ms内,它会被执行4次。

但是作者 完全错过了四次调用是什么意思?

所以,有两个任务。任务一计划每 10 毫秒执行一次 运行,任务二计划每 40 毫秒执行一次 运行。

假设在时间 0,任务二开始 运行ning,紧接着,任务一被触发:

0.0:任务 2 运行宁

0.1: 任务 1 已触发,任务 2 仍在 运行ning.

10.1: 任务 1 已触发,任务 2 仍在 运行ning

20.1 任务 1 已触发,任务 2 仍在 运行ning

30.1 任务 1 已触发,任务 2 仍在 运行ning

40.0:任务 2 完成,任务 1 开始 运行ning。

可以看到,从Task 2开始到Task 2结束,Task 1被触发了4次,没有机会运行。 此外,任务 1 将快速连续 运行 4 次,因为它被触发了 4 次但没有机会 运行.

这是代码示例:

public static void main(String[] args) throws Exception {
    final long start = System.currentTimeMillis();
    Timer timer = new Timer();

    // Schedule a new task that runs at a 10ms interval and stars immediately
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("10ms delayed task ran at " + (System.currentTimeMillis() - start));
        }
    }, 0, 10);

    // Schedule a task to start in 50ms that takes 40ms to run.
    // It cancels itself so it's only run once.
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("slow task ran at " + (System.currentTimeMillis() - start));
            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {

            }
            this.cancel();
        }
    }, 50, 10);

    // Wait 100 ms for the demo to end, then stop the timer.
    Thread.sleep(100);
    timer.cancel();
}

输出:

10ms delayed task ran at 1
10ms delayed task ran at 11
10ms delayed task ran at 22
10ms delayed task ran at 32
10ms delayed task ran at 42
slow task ran at 52
10ms delayed task ran at 92