简体   繁体   中英

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.

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. Depending on your need, that may be good enough.

But, quoting the javadoc of Timer :

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 .

If you want to simulate 1000(and more) clients acting simultaneously, you have to use Thread s! 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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