timer类安排任务在给定时间运行一次或重复。它还可以作为守护线程在后台运行。要将 timer 与守护线程关联起来,需要使用一个带有布尔值的构造函数。计时器以固定延迟和固定速率安排任务。在固定延迟下,如果任何一个执行被系统gc延迟,则其他执行也会延迟,并且每次执行都会延迟对应于之前的执行。在固定速率下,如果任何执行被系统gc延迟,则连续发生2-3次执行以覆盖与第一次执行开始时间相对应的固定速率。 timer 类提供了 cancel() 方法来取消计时器。当调用该方法时,定时器终止。 timer 类仅执行实现 timertask 的任务。
示例import java.util.*;public class timerthreadtest { public static void main(string []args) { task t1 = new task("task 1"); task t2 = new task("task 2"); timer t = new timer(); t.schedule(t1, 10000); // executes for every 10 seconds t.schedule(t2, 1000, 2000); // executes for every 2 seconds }}class task extends timertask { private string name; public task(string name) { this.name = name; } public void run() { system.out.println("[" + new date() + "] " + name + ": task executed!"); }}
输出[thu aug 01 21:32:44 ist 2019] task 2: task executed![thu aug 01 21:32:46 ist 2019] task 2: task executed![thu aug 01 21:32:48 ist 2019] task 2: task executed![thu aug 01 21:32:50 ist 2019] task 2: task executed![thu aug 01 21:32:52 ist 2019] task 2: task executed![thu aug 01 21:32:53 ist 2019] task 1: task executed![thu aug 01 21:32:54 ist 2019] task 2: task executed![thu aug 01 21:32:56 ist 2019] task 2: task executed![thu aug 01 21:32:58 ist 2019] task 2: task executed![thu aug 01 21:33:00 ist 2019] task 2: task executed!
以上就是我们如何在java中实现一个计时器线程?的详细内容。