gpt4 book ai didi

java - 使用单个计时器进行多个计划调用

转载 作者:行者123 更新时间:2023-12-01 14:07:34 24 4
gpt4 key购买 nike

我正在阅读有关 Java SDK 1.3 中的计时器的内容

POSA第2卷主动对象模式中提到如下

JDK 1.3 introduced a mechansim for executing timer-based tasks concurrently in the classes java.util.Timer and java.util.TimerTask. When ever the scheduled execution time of a task occurs it is executed. The scheduling calls are executed in the clinets thread, while the tasks themselves are executed in a thread owned by Timer object. A timer internal task queue is protected by locks because the two threads outlined above operate on it concurrently.

The task queue is implemented as a priority queue so that the next TimerTask to expire can be identified efficiently. The timer thread simply waits until this expiration.

public class Reminder {
Timer timer;

public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}

class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread
}
}

public static void main(String args[]) {
new Reminder(5);
System.out.format("Task scheduled.%n");
}
}

我的问题是

  1. 我们可以用一个定时器来实现多个调度函数吗?请求在这里给出一个例子以及它是如何工作的。例如,如果我们有两个计划,每 5 秒执行一个任务,如上所示,每 12 秒执行另一个任务,但我想使用相同的 Reminder 对象,而不是使用另一个(即创建)Reminder 对象。我想知道它的内部工作原理,就像计时器如何表示 5、5、2、3 等。 (因为我的项目有同样的要求,我必须在 C++ 中完成而不使用 boost。我计划使用单个计时器而不是多个计时器。

  2. 这里的延迟参数是什么以及如何使用它。 Schedule(TimerTask任务,长延迟,长周期)

感谢您的时间和帮助。

最佳答案

如果您不必使用 SDK 1.3,则可以使用 Java 5.0,它引入了 ScheduledExecutorService,恕我直言,这使得计时器变得多余。

ScheduledExecutorService已经存在9年多了,也许是时候升级了。

顺便说一句,在 Sun 正式确定生命周期结束日期之前,1.3 就已经生命周期结束了。它是古老的,除非你喜欢历史课,否则我建议你活在当下。 ;)

顺便说一句,Java 5.0 和 Java 6 都已结束生命周期,Java 7 将于明年宣布其生命周期结束日期。

所以,如果我是你,我会关注 Java 7 或 8,并忽略任何几年前的内容,因为互联网上有很多实践要么不好,要么过时,而且它们不被接受。已更新。

如果您喜欢了解不良或过时的做法,玫瑰印度网站是我发现的最好的集合。 ;)

关于java - 使用单个计时器进行多个计划调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18779485/

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