gpt4 book ai didi

java - ScheduledExecutorService#scheduleAtFixedRate 不起作用

转载 作者:行者123 更新时间:2023-11-30 05:57:56 24 4
gpt4 key购买 nike

当我定期执行一项耗时的任务时,结果没有达到我的预期。

public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

scheduler.scheduleAtFixedRate(() -> {
System.out.println("start: " + System.currentTimeMillis());
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end : " + System.currentTimeMillis());
}, 0, 1, TimeUnit.SECONDS);
}
/*
start: 1539688734439
end : 1539688737442
start: 1539688737443
end : 1539688740447
start: 1539688740447
end : 1539688743452
start: 1539688743452
end : 1539688746456
start: 1539688746456
end : 1539688749461
...
*/

如上所示,两次开始之间间隔 3 秒,而不是 1 秒。

最佳答案

这正是它的设计方式,来自 doc :

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

关于java - ScheduledExecutorService#scheduleAtFixedRate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52834337/

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