gpt4 book ai didi

java - Java 线程每秒常量 "ticks"

转载 作者:行者123 更新时间:2023-12-01 18:37:57 38 4
gpt4 key购买 nike

我知道这对于更有经验的程序员来说可能是完全显而易见的,但我找不到任何内容。

我需要创建一个线程,无论它必须执行的任务有多长,每秒都会以恒定的次数“滴答”。花费比每个滴答时间更长的任务显然是不可能的,并且会减慢每秒的滴答数。

谢谢。

最佳答案

使用java.util.Timer.scheduleAtFixedRate :

public void scheduleAtFixedRate(TimerTask task,
Date firstTime,
long period)

Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate). As a consequence of the above, if the scheduled first time is in the past, then any "missed" executions will be scheduled for immediate "catch up" execution.

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

关于java - Java 线程每秒常量 "ticks",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034883/

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