运行 java 中没有线程的计时器

Run timer without thread in java

我正在构建 运行 1000(和更多)个客户端的模拟器,在每个客户端中,我想在 X 时间后 运行 任务,我尝试了 TimerTask,问题是在每个任务(超过 1000 个)中创建新线程。

有没有没有线程的任务定时器?

您可以使用单个计时器安排多个 TimerTask,但它们不能同时 运行。根据您的需要,这可能就足够了。

但是,引用 Timer 的 javadoc:

Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

如果你想模拟 1000 个(或更多)客户端同时操作,你必须使用 Threads!否则,您将只有一个线程,其中您的明确逻辑指定何时完成什么客户端的逻辑 - 这实际上并不能模拟并行操作的客户端。