Threadpoolexecutor–java Thread Pool Example

Source: Internet
Author: User

Https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice

Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed. We can use the to ThreadPoolExecutor create the thread pool in Java.

Java thread Pool manages the collection of Runnable threads and worker threads execute Runnable from the queue. Java.util.concurrent.Executors provide implementation of Java.util.concurrent.Executorinterface to create the thread Pool in Java. Let's write a simple program to explain it ' s working.

First we need to has a Runnable class, named Workerthread.java

Package Com.journaldev.threadpool;public class Workerthread implements Runnable {      private String command;        Public Workerthread (String s) {        this.command=s;    }    @Override public    Void Run () {        System.out.println (Thread.CurrentThread (). GetName () + "Start. Command = "+command");        ProcessCommand ();        System.out.println (Thread.CurrentThread (). GetName () + "End.");    private void ProcessCommand () {        try {            thread.sleep ()        } catch (Interruptedexception e) {            E.printstacktrace ();        }    }    @Override public    String toString () {        return this.command;    }}
Executorservice Example

The. The test program Class SimpleThreadPool.java , where we are creating the fixed thread pool from the executors framework.

Package Com.journaldev.threadpool;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Simplethreadpool {public    static void Main (string[] args) {        Executorservice executor = Executors.newfixedthreadpool (5);        for (int i = 0; i < i++) {            Runnable worker = new Workerthread ("" + i);            Executor.execute (worker);          }        Executor.shutdown ();        while (!executor.isterminated ()) {        }        System.out.println ("Finished all Threads");}    }

In above program, we is creating fixed size thread pool of 5 worker threads. Then we were submitting jobs to this pool, since the pool size is 5, it would start working on 5 jobs and other jobs would Be-in-wait state, as-soon as one of the job is finished, another job from the wait queue would be a picked up by worker Thre AD and get ' s executed.

Here are the output of the above program.

Pool-1-thread-2 Start. Command = 1pool-1-thread-4 Start. Command = 3pool-1-thread-1 Start. Command = 0pool-1-thread-3 Start. Command = 2pool-1-thread-5 Start. Command = 4pool-1-thread-4 end.pool-1-thread-5 end.pool-1-thread-1 end.pool-1-thread-3 end.pool-1-thread-3 Start. Command = 8pool-1-thread-2 end.pool-1-thread-2 Start. Command = 9pool-1-thread-1 Start. Command = 7pool-1-thread-5 Start. Command = 6pool-1-thread-4 Start. Command = 5pool-1-thread-2 end.pool-1-thread-4 end.pool-1-thread-3 end.pool-1-thread-5 end.pool-1-thread-1 end.finished All Threads

The output confirms that there is five threads in the pool named from "Pool-1-thread-1" to "pool-1-thread-5" and they is Responsible to execute the submitted tasks to the pool.

Threadpoolexecutor Example

Executors class provide simple implementation of Executorservice using Threadpoolexecutor but Threadpoolexecutor provides Much more feature than. We can specify the number of threads that is alive when we create threadpoolexecutor instance and we can limit the SI Ze of thread pool and create our own Rejectedexecutionhandler implementation to handle the jobs that can ' t fit in the work ER queue.

Here are our custom implementation of Rejectedexecutionhandler interface.

Package Com.journaldev.threadpool;import Java.util.concurrent.rejectedexecutionhandler;import Java.util.concurrent.threadpoolexecutor;public class Rejectedexecutionhandlerimpl Implements Rejectedexecutionhandler {    @Override public    void Rejectedexecution (Runnable R, Threadpoolexecutor executor) {        System.out.println (r.tostring () + "is rejected");}    }

ThreadPoolExecutorProvides several methods using which we can find out the current state of executor, pool size, active thread count and Tas K count. So I had a monitor thread that would print the executor information at certain time interval.

Package Com.journaldev.threadpool;import Java.util.concurrent.threadpoolexecutor;public Class MyMonitorThread    Implements runnable{private Threadpoolexecutor executor;    private int seconds;    Private Boolean run=true;        Public Mymonitorthread (threadpoolexecutor executor, int delay) {this.executor = executor;    This.seconds=delay;    } public void Shutdown () {this.run=false; } @Override public void Run () {while (run) {System.out.println (string.f Ormat ("[Monitor] [%d/%d] Active:%d, completed:%d, Task:%d, IsShutDown:%s, isterminated:%s", th Is.executor.getPoolSize (), This.executor.getCorePoolSize (), this.executor.ge Tactivecount (), This.executor.getCompletedTaskCount (), This.executor.getTask Count (), This.executor.isShutdown (), this.executor.isTerminated ()));                try {thread.sleep (seconds*1000);                } catch (Interruptedexception e) {e.printstacktrace (); }        }                }}

The

Here is the thread pool implementation example Using threadpoolexecutor.

Package Com.journaldev.threadpool;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.executors;import Java.util.concurrent.threadfactory;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;public class WorkerPool {public static void Main (String args[]) throws interruptedexception{//rejectedexecutionhandler implementation Rejectedexec        Utionhandlerimpl Rejectionhandler = new Rejectedexecutionhandlerimpl ();        Get the Threadfactory implementation to use threadfactory Threadfactory = Executors.defaultthreadfactory (); Creating the Threadpoolexecutor threadpoolexecutor Executorpool = new Threadpoolexecutor (2, 4, ten, timeunit.se        Conds, New arrayblockingqueue<runnable> (2), threadfactory, Rejectionhandler);        Start the monitoring thread mymonitorthread monitor = new Mymonitorthread (Executorpool, 3);        Thread monitorthread = new thread (monitor); Monitorthread.starT (); Submit work to the thread pool for (int i=0; i<10; i++) {Executorpool.execute (New workerthread ("cmd")        +i));        } thread.sleep (30000);        Shut down the pool Executorpool.shutdown ();        Shut down the monitor thread Thread.Sleep (5000);            Monitor.shutdown (); }}

Notice that while initializing the threadpoolexecutor, we is keeping initial pool size as 2, maximum pool size to 4 and W Ork queue size as 2. So if there is 4 running tasks and more tasks is submitted, the work queue would hold only 2 of them and rest of them wil l am handled by RejectedExecutionHandlerImpl .

Here is the output of above program, that confirms above statement.

Pool-1-thread-1 Start. Command = Cmd0pool-1-thread-4 Start. Command = Cmd5cmd6 is rejectedpool-1-thread-3 Start. Command = Cmd4pool-1-thread-2 Start. Command = Cmd1cmd7 is Rejectedcmd8 are Rejectedcmd9 is rejected[monitor] [0/2] active:4, completed:0, Task:6, IsShutDown : false, Isterminated:false[monitor] [4/2] active:4, completed:0, Task:6, Isshutdown:false, ISTERMINATED:FALSEPOOL-1 -thread-4 end.pool-1-thread-1 end.pool-1-thread-2 end.pool-1-thread-3 end.pool-1-thread-1 Start. Command = Cmd3pool-1-thread-4 Start. Command = Cmd2[monitor] [4/2] active:2, Completed:4, Task:6, Isshutdown:false, Isterminated:false[monitor] [4/2] Acti Ve:2, Completed:4, Task:6, Isshutdown:false, Isterminated:falsepool-1-thread-1 end.pool-1-thread-4 End. [Monitor] [4/2] active:0, Completed:6, Task:6, Isshutdown:false, Isterminated:false[monitor] [2/2] active:0, Completed:6, Task:6, Isshutdown:false, Isterminated:false[monitor] [2/2] active:0, Completed:6, Task:6, isshutdown:falsE, Isterminated:false[monitor] [2/2] active:0, Completed:6, Task:6, Isshutdown:false, Isterminated:false[monitor] [2  /2] active:0, Completed:6, Task:6, Isshutdown:false, Isterminated:false[monitor] [2/2] active:0, Completed:6, Task: 6, Isshutdown:false, Isterminated:false[monitor] [0/2] active:0, Completed:6, Task:6, Isshutdown:true, isTerminated : True[monitor] [0/2] active:0, Completed:6, Task:6, Isshutdown:true, isterminated:true

Notice the change in active, completed and total completed task count of the executor. We can invoke shutdown () method to finish execution of all the submitted tasks and terminate the thread pool.

If you want to schedule a task to run with delay or periodically and then you can use Scheduledthreadpoolexecutor class. Read more about them at Java Schedule Thread Pool Executor.

Threadpoolexecutor–java Thread Pool Example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.