The implementation of five kinds of thread pools commonly used in Java

Source: Internet
Author: User
thread pool Description:Multithreading technology mainly solves the problem of multiple threads executing in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput capacity of the processor unit. Suppose a server completes a task by the time it takes to create the thread time, T2 the time of the task in the thread, T3 destroy the thread time. T1
interfaces and classes involved: A. Threadpoolexecutor class in Java (This class has four methods of construction)Public threadpoolexecutor (int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit Unit, BlockingQueue <Runnable> workqueue);
Public threadpoolexecutor (int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit Unit, BlockingQueue <Runnable> workqueue,threadfactory threadfactory);
Public threadpoolexecutor (int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit Unit, BlockingQueue <Runnable> Workqueue,rejectedexecutionhandler handler);
Public threadpoolexecutor (int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit Unit, BlockingQueue< runnable> workqueue,threadfactory Threadfactory,rejectedexecutionhandler handler);
two. Executorservice interface in JavaCache thread Pool
Executors.newcachedthreadpool ();
Fixed long thread pool Executors.newfixedthreadpool (3);
Fixed long thread pool, timer executors.newscheduledthreadpool (3);

single-threaded thread pool executors.newsinglethreadexecutor ();
three. Scheduledexecutorservice interface in Java
Code implementation: The code has a detailed comment on each method, please read the comments carefully;

Package com.superb.juint_thread;
Import Java.util.concurrent.ArrayBlockingQueue;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.ThreadPoolExecutor;

Import Java.util.concurrent.TimeUnit; /** * There are five ways to implement a thread pool in this class, three of which are implemented through the Executorservic interface, one is implemented through the Scheduledexecutorservice interface, and the other is implemented through the Threadpoolexecutor class. The five thread pools are implemented in single case mode, and there is no need for a single example mode to be implemented, which is based entirely on the business needs of the project * * @author Superb * */public class Threadpoolutil {private static T

	Hreadpoolexecutor pool = null;
	
	/** Cache thread Pool */private static executorservice Cachedpool = null;
	
	/** Fixed long thread pool * * private static Executorservice fixedpool = null;
	
	/** fixed long thread pool, support timed and periodic * * private static Scheduledexecutorservice schedulpool = null;
	
	
	/** Single Example thread pool * * private static Executorservice singlepool = null; Private Threadpoolutil () {}/** * gets a threadpoolexecutor thread pool * New Threadpoolexecutor (int corepoolsize, int maximu MpoolSize, * Long KeepAliveTime, timeunit unit, Blockingqueue workqueue, * Rejectedexecutionhandler handler) * * @corePoolSize thread pool Size * @maximumPoolSize The maximum number of threads pools * @keepAliveTime The lifetime of a thread save * @workQueue a thread exceeds the thread size, the task exists in this queue * @h When the Andler thread exceeds the queue, the processing method * @return/public static Threadpoolexecutor newinstance () {if (pool==null) {synchronized (Th Readpoolutil.class) {if (pool==null) {pool = new Threadpoolexecutor (3, 5, timeunit.seconds, new ARRAYBL
				Ockingqueue (a), New Threadpoolexecutor.discardoldestpolicy ());
	}} return pool;
	 /** * Creates a cache thread pool that can be flexibly recycled if the thread pool length exceeds the processing needs, and if there is no recyclable, create a new thread. 
	 * * The thread pool is infinite, the first task is completed when the second task is performed, and the thread that executes the first task is reused instead of creating a new thread at a time.  * @return Cachedthreadpool */public static Executorservice Cachedinstance () {if (Cachedpool = = null) {synchronized
				(Threadpoolutil.class) {if (cachedpool==null) {cachedpool = Executors.newcachedthreadpool ();
	}} return Cachedpool; /** * Create a thread-length pool to control threadsThe maximum number of concurrent digits, and the threads that are exceeded will wait in the queue. (The thread pool size is 3) * * The size of the pool is best set according to system resources * * @return Cachedthreadpool/public static Executorservice Fixedinsta nCE () {if (Fixedpool = = null) {synchronized (Threadpoolutil.class) {if (fixedpool==null) {Fixedpool = Executo
				Rs.newfixedthreadpool (3);
	}} return Fixedpool;  /** * Create a fixed-line pool that supports timed and recurring task Execution (timed task) * * @return Cachedthreadpool/public static Scheduledexecutorservice Schedulinstance () {if (Schedulpool = = null) {synchronized (Threadpoolutil.class) {if (schedulpool==null) {SC
				Hedulpool = Executors.newscheduledthreadpool (3);
	}} return Schedulpool;
	 /** * Creates a single-threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks perform each task in the order of the specified order (FIFO, LIFO, priority).  * @return Cachedthreadpool */public static Executorservice SingleInstance () {if (Singlepool = = null) {synchronized
				(Threadpoolutil.class) {if (singlepool==null) {Singlepool = Executors.newscheduledthreadpool (10);	}
			}
		}
		return singlepool;

}} package Com.superb.juint_thread;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.concurrent.ExecutorService;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.ThreadPoolExecutor;

Import Java.util.concurrent.TimeUnit; 
    	/** * Test thread pool Implementation main CLASS * */public class ThreadMain {public static void main (string[] args) {//singlemethod ();
    	Cachedmethod ();
    	Schedulmethod ();
    	Fixedmethod ();
    Threadpoolmethod ();
     /** * Description: * Get a Threadpoolexecutor thread pool, * implemented by the new Threadpoolexecutor () object class.
     * This method is new (@corePoolSize) thread pool size 3. * 10 simulation tasks, three per execution, remaining in queue for execution * Result: *---------------BEGIN--------------*---------------EN D--------------*-----------pool-1-thread-1---2016-08-12 05:47:13 *-----------pool-1-thread-2---2016-08-12 05: 
47:13 *-----------pool-1-thread-3---2016-08-12 05:47:13 *     *-----------pool-1-thread-1---2016-08-12 05:47:15 *-----------pool-1-thread-3---2016-08-12 05:47:15 *--- --------pool-1-thread-2---2016-08-12 05:47:15 * *-----------pool-1-thread-1---2016-08-12 05:47:17 *----- ------pool-1-thread-3---2016-08-12 05:47:17 *-----------pool-1-thread-2---2016-08-12 05:47:17 * *------- ----pool-1-thread-3---2016-08-12 05:47:19 * * public static void Threadpoolmethod () {Threadpoolexecutor pool
		= Threadpoolutil.newinstance ();
    	System.out.println ("---------------BEGIN--------------"); for (int i = 0; i < i++) {Pool.execute (The new Runnable () {public void run () {System.out.println ( "-----------" +thread.currentthread (). GetName () + "---" +new simpledateformat ("Yyyy-mm-dd hh:mm:ss"). Format (New Dat
    				E ()));
					try {thread.sleep (2000);
					catch (Interruptedexception e) {e.printstacktrace ();
    	}
    			}
    		}); } System.out.println ("---------------end--------------"); /** * Description: * Timer, you can specify the business at a specified time to execute once, the method every 3 seconds to simulate a business process * Result: * * Simulation Business processing =====2016-0  8-12 04:30:37 * Analog Business processing =====2016-08-12 04:30:40 * Analog Business processing =====2016-08-12 04:30:43 * Analog Business processing =====2016-08-12 04:30:46 * Analog Business Processing =====2016-08-12 04:30:49 * * public static void Schedulmethod () {Scheduledexecutorservice pool = Threa
    	Dpoolutil.schedulinstance (); Pool.scheduleatfixedrate (New Runnable () {public void run () {System.out.println ("Simulate business processing =====" +new SimpleDateFormat
			("Yyyy-mm-dd hh:mm:ss"). Format (new Date ());
    }, 0, 3, timeunit.seconds);
	 /** * Description: * The thread pool is infinite, when the second task is done, the first task is completed, and the thread that executes the first task is reused instead of creating a new thread at a time.
	 * Conclusion: * When each task executes 5s with a task interval of 2s, the next task is already started when the previous task is not finished, and the previous thread is not reused.   * When the task is 2s, the task interval is 5s, the next task begins, the last task is completed, and the previous thread is reused. * Result 1: *
----------->BEGIN<-------
*
------>pool-1-thread-1<------
*
------>pool-1-thread-2<------
*
------>pool-1-thread-3<------
*
------>pool-1-thread-1<------
*
------>pool-1-thread-2<------
*
------>pool-1-thread-3<------
*
----------->SUCCESS<------
* Result 2: *
----------->BEGIN<-------
*
------>pool-1-thread-1<------
*
------>pool-1-thread-1<------
*
------>pool-1-thread-1<------
*
------>pool-1-thread-1<------
*
----------->SUCCESS<------
*/public static void Cachedmethod () {Executorservice pool = threadpoolutil.cachedinstance (); System.out.println ("
----------->BEGIN<-------
"); for (int i = 0; i < i++) {Pool.execute (The new Runnable () {public void run () {System.out.println ()
------> "+ thread.currentthread (). GetName () +" <------
"); try {thread.sleep (5000);//per Task execution 5s,} catch (Interruptedexception e) {e.printstacktrace ();}} }); try {thread.sleep (2000);//per task interval 2s} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println ("
----------->SUCCESS<------
"); } /** * Description: * Fixed long thread pool, can control the maximum number of concurrent threads, more than threads will wait in the queue, * This method we implemented a 3-length thread pool, which opened 10 tasks, each time only 3 tasks,
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.