I am trying to understand how Executor.submit(Runnable) works. Suppose we create a thread pool of size 2 using ExecutorService.
We have a class called Runner implements Runnable.
ExecutorService.newFixedThreadPool(2);
for (int i = 0; i <5; i++){
ExecutorService.submit(new Runner());
}
When we do new Runner() are we not creating 5 threads already?
So how does ExecutorService help in this case?
The service uses a queue to store the incoming Runnable objects. As soon as a thread becomes available to do work, the service uses that thread to execute the next Runnable object that is due.
Runnables are not Threads. Your example will create two threads which make up the pool; and then the 5 Runner objects will be dispatched to one of those two threads over time.
That is all there is to this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With