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

标签 java multithreading

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

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

谢谢。

最佳答案

使用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/

相关文章:

java - 同步发出声音

java - 使用 Comparable 接口(interface)返回字符串、日期、整数的最大值的程序

java - 单独的线程来更改标签图标

python - Tornado 错误: cannot switch to a different thread

java - 将native方法定义为public native synchronized int doSum(int a, int b)对吗?

java - Servlet 似乎没有以线程方式执行

Java将字节数组转换为UTF-8字符串

java - 奇怪的 BufferStrategy 问题 - 游戏仅在 Intel GPU 上运行快速

c++ - 是否可以限制 C++ 17 并行 `for_each` 的线程数?

multithreading - 从非 UI QThread 修改 QStandardItemModel?