Java Thread Pool with Executor Framework

 


Java Thread pool manages the pool of threads which are under runnable state. Thread pools contains list of all Threads in queue which are waiting to get executed. Also Thread pool can be described as collection of Runnable Objects or instance. Thread pool will be constantly running and are checking the work query for new work or Thread to be added into the pool. If there are new work or Thread to be added into the pool and executed through Thread Pool. In Java Thread class itself provides a method, e.g. execute(Runnable r) to add a new Runnable object to the work queue and execute() method will take on executing each thread in the pool.

The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination. Suppose if you want to use 1 thread pool with only 1 thread which executes several runnables you can use the Executors.newSingleThreadExecutor() method.


public class MyRunnableClass implements Runnable {

 private int value;

 MyRunnableClass(int value) {
  this.value = value;
 }

 @Override
 public void run() {
  int total = 0;
  for (int i = 1; i < value; i++) {
   total += i;
  }
  System.out.println(Thread.currentThread().getName() + " : " + total);  
 }
}


public class ThreadPoolTest {

 public static void main(String[] args) {
  // Thread pool size set as "5"
  ExecutorService executor = Executors.newFixedThreadPool(5);
  // Total 25 threads we are creating
  for (int i = 1; i <= 25; i++) {
   Runnable worker = new MyRunnableClass(i);
   executor.execute(worker);
  }
  executor.shutdown();
  System.out.println("All Threads finished...");
 }
}


OUTPUT:


pool-1-thread-1 : 0
pool-1-thread-1 : 15
pool-1-thread-1 : 21
pool-1-thread-1 : 28
pool-1-thread-1 : 36
pool-1-thread-1 : 45
pool-1-thread-1 : 55
pool-1-thread-1 : 66
pool-1-thread-1 : 78
pool-1-thread-1 : 91
pool-1-thread-1 : 105
pool-1-thread-1 : 120
pool-1-thread-1 : 136
pool-1-thread-1 : 153
pool-1-thread-1 : 171
pool-1-thread-1 : 190
pool-1-thread-1 : 210
pool-1-thread-1 : 231
pool-1-thread-1 : 253
pool-1-thread-1 : 276
pool-1-thread-1 : 300
All Threads finished...
pool-1-thread-3 : 3
pool-1-thread-4 : 6
pool-1-thread-2 : 1
pool-1-thread-5 : 10



No comments:
Write comments