简体   繁体   English

在Java中不带线程运行计时器

[英]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 the ScheduledThreadPoolExecutor 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 the Timer / TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable ). 实际上,它是Timer / TimerTask组合的更通用的替代品,因为它允许多个服务线程,接受各种时间单位,并且不需要子类化TimerTask (只需实现Runnable )。 Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer . 使用一个线程配置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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM