Executors.newFixedThreadPool(5) creates 5 threads in the pool, and then in the loop another 100 threads are created. Is this understanding right? Then the 5 threads in the pool will execute each thread in the queue of 100 worker thread.
This is not correct. The fixed-size thread pool executor will create 5 worker threads. Your 100 Runnable
s are all added to a queue that these 5 threads are pulling from. So only 5 of your Runnable
s are executing at any given time. There are 5 threads (plus the main thread, and possibly the EDT if you're using Swing, and of course any other unrelated threads that you've explicitly created).
I had thought only 5 threads are created, but each Runnable is also a thread.
A Runnable
is not a thread. A Runnable
, as its name implies, is just something that can be run. In the case of the fixed-size thread pool, it is being run by one of the threads in the pool. From the documentation for Runnable
(emphasis mine):
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
I believe the source of your confusion may be that your Runnable
s are innapropriately named WorkerThread
, even though they are not threads. Additionally, you may be confused by the fact that Thread
also implements Runnable
. In fact, this literally means that a Thread
is a Runnable
, not that a Runnable
is a Thread
-- and a Thread
isn't even a thread until it's started.