«Back to Home

Core Java

Topics

Thread Pool In Java

Thread Pool
 
Thread pool is a group of worker threads, which are waiting for the job and it can be reused many times.
 
A group of fixed size threads are created in a thread pool. A thread from the thread pool is selected and is assigned a job by the Service provider.After completion his job, thread is contained in the thread pool again.
 
Advantage of Thread Pool

Its main advantage is it saves time and better performance because there is no need to create new thread.
 
Usage of Thread Pool

It is mainly used in Servlet and JSP in which Web or Servlet container creates a thread pool to process the request.
 
Let’s see an example, given below.
 
Code
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3. public class ThreadPoolExample implements Runnable {  
  4.     private String thread;  
  5.     public ThreadPoolExample(String t) {  
  6.         this.thread = t;  
  7.     }  
  8.     public void run() {  
  9.         System.out.println(Thread.currentThread().getName() + " Start thread = " + thread);  
  10.         processmessage(); //sleeps the thread for 2 seconds    
  11.         System.out.println(Thread.currentThread().getName() + " End "); //prints thread name    
  12.     }  
  13.     private void processmessage() {  
  14.         try {  
  15.             Thread.sleep(1500);  
  16.         } catch (InterruptedException e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  
  20. }  
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3. public class PoolTest {  
  4.     public static void main(String[] args) {  
  5.         ExecutorService e = Executors.newFixedThreadPool(3); //creating a pool of 3 threads    
  6.         for (int i = 0; i <= 6; i++) {  
  7.             Runnable t = new ThreadPoolExample("" + i);  
  8.             e.execute(t);  
  9.         }  
  10.         e.shutdown();  
  11.         while (!e.isTerminated()) {}  
  12.         System.out.println("All threads are finish");  
  13.     }  
  14. }  
29

30
 
Output

31

Summary

Thus, we learnt, thread pool is a group of worker threads, which are waiting for the job and it can be reused many times and also learnt, how to create it in Java.