TODAY JAVA SCHOOL

In java school, programming, design, computer general knowledge, web application, software, web services, social media, digital marketing, oops, concept of programming language, oops feature, console media, graphics medium, first programming, c, c ++ , Java, PHP, SQL, MySQL, HTML, HTML_5, J_query, JavaScript, Bootstrap, Framework, images with logos, examples, shared and explained.

https://www.amazon.in/b?node=26373545031&linkCode=ll2&tag=1234567801cdb-21&linkId=3b9882431b00409b44141e0344b35a15&language=en_IN&ref_=as_li_ss_tl

Breaking

Wednesday, 15 April 2020

Thread Pool Implementation In Java | Advantage Of Thread Pool In Java | Java Thread Pool

Java Thread Pool

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

thread pool implementation in java | custom thread pool in java


Fig: Thread Pool

Advantage of Java Thread Pool

Better performance It saves time because there is no need to create new thread.

Real time usage

It is used in Servlet and JSP where container creates a thread pool to process the request.

Example of Java Thread Pool


     import java.util.concurrent.ExecutorService;  
     import java.util.concurrent.Executors;  
    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);  
        processmessage();//call processmessage method that sleeps the thread for        2 seconds  
        System.out.println(Thread.currentThread().getName()+" (End)");//prints      thread name  
    }  
    private void processmessage() {  
        try {  Thread.sleep(2000);  } catch (InterruptedException e) { e.printStac       kTrace(); }  
    }  
     }  

    

      JavaThreadPoolExample.java

   
     public class TestThreadPool {  
     public static void main(String[] args) {  
        ExecutorService executor = Executors.newFixedThreadPool(5);//creating a    pool of 5 threads  
        for (int i = 0; i < 10; i++) {  
            Runnable worker = new WorkerThread("" + i);  
            executor.execute(worker);//calling execute method of ExecutorService  
          }  
        executor.shutdown();  

       

No comments:

Post a Comment