Thread pool is collection of threads, which is created to complete certain tasks. We will be creating fixed thread pool using executors framework. The interaction between thread pool and task is as follows:
- Thread Pool is created
- Create a task by implementing Runnable interface.
- Task is assigned to a thread from fixed size thread pool.
- Thread executes and finishes the task.
- Thread return back to thread pool, to execute another task.
Program to implement fixed size thread pool in java using Executors framework
package org.blog.learn; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class MyThread implements Runnable { private String msg; public MyThread(String msg) { this.msg = msg; } public void run() { // Start of step 4 System.out.println(" Starting :" + Thread.currentThread().getName()); System.out.println("Thread Msg : " + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { // skipping the catch as of now } System.out.println(" Ending :" + Thread.currentThread().getName()); } /// End of step 4 } public class MyThreadPool { public static void main(String[] args) { // Step No 1 ExecutorService executor = Executors.newFixedThreadPool(2); for (int number = 0; number < 4; number++) { // Step No 2 Runnable worker = new MyThread("Thread " + number); // Step No 3 executor.execute(worker); } executor.shutdown(); // Waiting for all thread to finish while (!executor.isTerminated()) ; System.out.println("All threads finished"); } }
Output create fixed thread pool using executor framework
Starting :pool-1-thread-1 Starting :pool-1-thread-2 Thread Msg : Thread 1 Thread Msg : Thread 0 Ending :pool-1-thread-1 Ending :pool-1-thread-2 Starting :pool-1-thread-1 Starting :pool-1-thread-2 Thread Msg : Thread 2 Thread Msg : Thread 3 Ending :pool-1-thread-1 Ending :pool-1-thread-2 All threads finished