Tuesday, 1 August 2017

Thread Pool in Java with example of matrix addition

                 In this post, we will see what is threadpool in Java along with an example of two matrices addition.



 What is Threadpool?

                 Threadpool is a concept in Java. It refers to the collection of threads i.e. a group of fixed size of threads.

How it works?

                 A thread is taken (i.e. pulled) from thread pool and task is allocated to it. Similarly, other threads are taken from thread pool and tasks are allocated to them. When task is completed, thread is returned to the thread pool. A returned thread in thread pool can be pulled back again and can be allocated a new task.



                 Suppose there are three threads in a thread pool and five tasks.
                 
(First Thread=First Task) First thread will be allocated first task.
(Second Thread=Second Task) Second thread will be allocated second task.
(Third Thread=Third Task) Third thread will be allocated third task.

Once the first or second or third thread will be free i.e. completed task; it will return to thread pool and it will be allocated fourth task.


Again whoever thread gets free will return back to thread pool and will be allocated fifth task.

                             



Advantage of Thread Pool:
                 Thread Pool reuses the threads. That's why, it reduces the time for creating new threads.
                 Java Thread Pool can be used with Servlet or JSP.

                 Go through the following example:

                 Here we are adding two matrices with 2 rows and 3 columns. We are creating a thread pool with 4 threads.

ThreadPoolMatrixAddition.java 

 import java.util.concurrent.*;  

class WorkerThread implements Runnable 
{  
    private int row;
    private int col; 
    int x[][]={{1,2,3},{4,5,6}};
    int y[][]={{1,2,3},{4,5,6}};
    static int z[][]=new int[2][3];    
  
    public WorkerThread(int i, int j)
    {  
        this.row=i;  
        this.col=j;
    }  
     public void run() 
    {  
        z[row][col]=x[row][col]+y[row][col];
        System.out.println("z["+row+"]["+col+"]=x["+row+"]["+col+"]+y["+row+"]["+col+"] calculated by "+Thread.currentThread().getName()); 
    }  
     


public class ThreadPoolMatrixAddition 
{  
     public static void main(String[] args) 
    {  
        ExecutorService executor = Executors.newFixedThreadPool(4);//creating a pool of 4 threads  
               
        for (int i = 0; i < 2; i++) 
         for (int j = 0; j < 3; j++)
          {  
            Runnable worker = new WorkerThread(i,j);  
            executor.execute(worker);//calling execute method of ExecutorService  
          } 

       executor.shutdown();//shutdown() will not allow allocating new tasks to threads but will wait till the completion of all allocated tasks

       while (!executor.isTerminated()) { } 

       System.out.println();
        
       for (int i = 0; i < 2; i++) 
         for (int j = 0; j < 3; j++) 
          {  
            System.out.println("z["+i+"]["+j+"]="+WorkerThread.z[i][j]);
          } 
       
       System.out.println();          
       System.out.println("Finished all threads");  
    }  
 }  
  
Output:
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac ThreadPoolMatrixAddition.java 
parag@parag-Inspiron-N4010:~/Desktop/prog$ java ThreadPoolMatrixAddition
z[0][0]=x[0][0]+y[0][0] calculated by pool-1-thread-1
z[0][2]=x[0][2]+y[0][2] calculated by pool-1-thread-3
z[1][0]=x[1][0]+y[1][0] calculated by pool-1-thread-4
z[0][1]=x[0][1]+y[0][1] calculated by pool-1-thread-2
z[1][2]=x[1][2]+y[1][2] calculated by pool-1-thread-3
z[1][1]=x[1][1]+y[1][1] calculated by pool-1-thread-1

z[0][0]=2
z[0][1]=4
z[0][2]=6
z[1][0]=8
z[1][1]=10
z[1][2]=12

Finished all threads



Check other posts on Multi-Threading in this link http://www.comrevo.com/2016/09/multi-threading.html


10 comments:

  1. The post is written in very a good manner and it entails many useful information for me. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept.
    Click here:
    angularjs training in rajajinagar
    Click here:
    angularjs training in marathahalli

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ReplyDelete
  3. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging

    ReplyDelete
  4. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete