Thread pool in java

Normally, server creates a new thread when a new request comes. This approach have several disadvantages. For creating a new thread for every new request will take more time and resources. Thread pool concept is introduced to resolve these problems.

Thread pool in java

A thread pool represents a group of threads which are waiting the job and can be used many times. In case of thread pool, when a new request comes then instead of creating a new thread, the job can be passed to thread pool.

Note: Thread pool helps us to limit the number of threads running in our application.

Example

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class ThreadPoolTest {
  public static void main(String[] args) {
	  ExecutorService executor = Executors.newFixedThreadPool(3);
      for (int i = 0; i < 5; i++) {  
          Runnable worker = new WorkerThread("" + i);  
          executor.execute(worker); 
        }  
      executor.shutdown();  
      while (!executor.isTerminated()) {   }  
 
      System.out.println("All threads are finished.");  
  }
}
 
class WorkerThread implements Runnable {  
    private String message;  
    public WorkerThread(String s){  
        this.message=s;  
    }  
     public void run() {  
        System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
        System.out.println(Thread.currentThread().getName()+" (End)"); 
    }   
}

Output

pool-1-thread-1 (Start) message = 0
pool-1-thread-3 (Start) message = 2
pool-1-thread-2 (Start) message = 1
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 4
pool-1-thread-3 (End)
pool-1-thread-1 (End)
pool-1-thread-2 (End)
All threads are finished.
Content Protection by DMCA.com
Please Share