Thread Pool Example
I will now show you an example of how to use the thread pool. First, you must crate a class that implements the Runnable interface and contains a run method that will execute your task. An example class that does this is shown in Listing 3.
This is a very simple task that counts from zero to 100 percent. This count takes a random amount of time. The countdown is implemented in the run method of the TestWorkerThread. The main program, which is shown in Listing 4, will create 50 of these TestWorkerThread classes and assign them to the thread pool. The ThreadPool will execute up to 10 tasks at a time. After the program is running, you will see 10 of the threads counting their percent up to 100. Once one of these ten completes, another is chosen from the waiting assignments.