- When to Use Multithreading
- Why a Thread Pool?
- Implementing the Thread Pool
- Are We Done Yet?
- Thread Pool Example
- Conclusions
Implementing the Thread Pool
The main class file that makes up my thread pool is the ThreadPool.java source file (this source file can be seen in Listing 1 at the end of the article). The listing is well-documented, and should allow you to understand the details of the program. I will now explain the general flow of the program.
The thread pool contains an array of WorkerThread objects. These objects are the individual threads that make up the pool. The WorkerThread objects will start and stop as work arrives for them. If there is more work than there are WorkerThreads, the work will backlog until WorkerThreads free up.
When you first create a new ThreadPool object the WorkerThreads are initially paused, waiting for work. You assign work to the ThreadPool using the assign method. Any class that implements the Runnable interface can be passed to the assign method. The assign method places the object into assignments array, in which it is picked up by a waiting thread.