gpt4 book ai didi

java - 下面示例中的重复任务 “misses” 四次调用是如何完成的?

转载 作者:行者123 更新时间:2023-12-01 21:15:26 25 4
gpt4 key购买 nike

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次。

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

最佳答案

这是代码示例:

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

关于java - 下面示例中的重复任务 “misses” 四次调用是如何完成的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com