[英]Run timer without thread in java
I am building simulator that run 1000(and more) clients, in each client i want to run task after X time, i tried TimerTask
, the problem is that in each task(more than 1000) new thread is created. 我正在构建运行1000个(及更多)客户端的模拟器,在每个要在X时间后运行任务的客户端中,我尝试了
TimerTask
,问题是在每个任务(超过1000个)中创建了新线程。
Did there as any task timer without thread? 是否有没有线程的任务计时器?
You can schedule multiple TimerTasks using a single Timer, they just can't run at the same time. 您可以使用单个Timer调度多个TimerTask,但它们不能同时运行。 Depending on your need, that may be good enough.
根据您的需要,这可能就足够了。
But, quoting the javadoc of Timer : 但是,引用Timer的javadoc:
Java 5.0 introduced the
java.util.concurrent
package and one of the concurrency utilities therein is theScheduledThreadPoolExecutor
which is a thread pool for repeatedly executing tasks at a given rate or delay.Java 5.0引入了
java.util.concurrent
包,其中的并发实用程序之一是ScheduledThreadPoolExecutor
,它是一个线程池,用于以给定的速率或延迟重复执行任务。 It is effectively a more versatile replacement for theTimer
/TimerTask
combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassingTimerTask
(just implementRunnable
).实际上,它是
Timer
/TimerTask
组合的更通用的替代品,因为它允许多个服务线程,接受各种时间单位,并且不需要子类化TimerTask
(只需实现Runnable
)。 ConfiguringScheduledThreadPoolExecutor
with one thread makes it equivalent toTimer
.使用一个线程配置
ScheduledThreadPoolExecutor
使其等效于Timer
。
If you want to simulate 1000(and more) clients acting simultaneously, you have to use Thread
s! 如果要模拟1000个(和更多)同时执行的客户端,则必须使用
Thread
! Otherwise you would have a single Thread in which your definite logic specifies when what logic of what client is done - that really does not simulate the clients acting in parallel. 否则,您将只有一个线程,在其中您的确定逻辑将指定何时完成什么客户端的逻辑-实际上不会模拟并行执行的客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.