'Execute a single task with multiple threads on a schedule
I have a function foo()
that I want to be invoked by multiple threads on an interval. example: want to execute foo() every 100ms with x number of threads. I am unsure how to go about it.
I am looking at FixedThreadPool where you can instantiate a thread pool with number of workers. However when you invoke using this thread pool does it exhaust all threads at once and executes a task?
any ideas would be appreciated; thanks
Solution 1:[1]
For a single task being repeated, you do not need multiple threads.
Use a single-threaded scheduled executor service.
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;
Define your task as a Runnable
or Callable
.
Runnable task = … ;
Schedule for repeated execution.
ScheduledFuture future = ses.scheduleWithFixedDelay( task , 0 , 100 , TimeUnit.MILLISECONDS ) ;
All of this has been covered many times already on Stack Overflow. Search to learn more.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Basil Bourque |