Java Thread Pool

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again. One potential advantage of thread pool is that it saves time because there is no need to create new thread. thread pool is used in Servlet and JSP where container creates a thread pool to process the request.

Let's see a simple example of java thread pool using ExecutorService and Executors.

File: WorkerThread.java


\begin{lstlisting}
import java.util.concurrent.ExecutorService;
import java.uti...
...catch (InterruptedException e) { e.printStackTrace(); }
}
}
\end{lstlisting}

File: JavaThreadPoolExample.java


\begin{lstlisting}
public class TestThreadPool {
public static void main(Strin...
... }
\par
System.out.println(''Finished all threads'');
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) m...
...ool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
\end{lstlisting}