Optimizing multithreaded programming with a thread pool
Understanding Thread Pools
In Java, all objects need to be created with the new operator,
If you create a large number of short-life-cycle objects, the performance of the entire program will be very low.
This is the time to use the technology of the pool, such as database connection pool, thread pool and so on.
After java1.5, Java comes with a thread pool and adds a concurrent package under the Util package.
The main purpose of this package is to introduce how Java threads and thread pools are used.
The executors class under package java.util.concurrent defines executor, Executorservice, Scheduledexecutorservice,
Threadfactoryscheduledexecutorservice, Threadfactory and callable plants and practical methods.
This class supports the following various methods :
A. Create and return a method that sets the executorservice of a common configuration string.
B. Create and return a method that sets the scheduledexecutorservice of a common configuration string.
C. Create and return a "wrapped" Executorservice method that disables reconfiguration by making the implementation-specific method inaccessible.
D. Create and return a Threadfactory method that sets the newly created thread to a known state.
E. Create and return a method for callable in a non-enclosed form, which can be used in an execution method that requires callable.
--If you want to reprint this article please indicate the reprint address "hhttp://www.cnblogs.com/xhjt/p/3905018.html" Thank you--
First, let's compare the differences between creating multiple threads with a thread pool and creating multiple threads in a stand-alone way.
Here we will illustrate the necessity and importance of thread pooling by comparing two methods to occupy memory and spend time .
code example:
PackageCom.xhj.thread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Compare the pros and cons of creating threads independently and thread pools-time and memory consumption * *@authorXiehejun **/ Public classComparethreadpoolImplementsRunnable {Private intID = 0; @Override Public voidrun () {ID++; } Public Static voidMain (string[] args) {/*** Create 1000 threads independently*/ { //Gets the current program run-time objectRuntime Run =Runtime.getruntime (); //call the garbage collection mechanism to reduce memory errorsRun.gc (); //gets the free memory of the current JVM LongFreememory =run.freememory (); //System Current Time LongTimepro =System.currenttimemillis (); //Create and execute 1000 of threads independently for(inti = 0; i < 1000; i++) { NewThread (NewComparethreadpool ()). Start (); } System.out.println ("The amount of memory required to create and execute 1000 threads independently:" + (Freememory-run.freememory ())); System.out.println ("The time required to create and run 1000 threads independently is:" + (System.currenttimemillis ()-Timepro)); } /*** Create 1000 threads using a thread pool*/ { //Gets the current program run-time objectRuntime Run =Runtime.getruntime (); //call the garbage collection mechanism to reduce memory errorsRun.gc (); //gets the free memory of the current JVM LongFreememory =run.freememory (); //System Current Time LongTimepro =System.currenttimemillis (); Executorservice Service= Executors.newfixedthreadpool (2); //Create and execute 1000 of threads independently for(inti = 0; i < 1000; i++) {Service.submit (NewComparethreadpool ()); } System.out.println ("The amount of memory that is required to create 1000 threads using a thread pool:" + (Freememory-run.freememory ())); //thread pool usage complete, closing thread poolsService.shutdown (); System.out.println ("The time required to create and run 1000 threads using the thread pool is:" + (System.currenttimemillis ()-Timepro)); } }}
The result is:
conclusion-Why use a thread pool:
From the above example, we know that using the thread pool can greatly improve the performance of the system and improve the execution efficiency of the program tasks.
Saves the memory space of the system. In the thread pool, each worker thread can be reused to perform multiple tasks,
Reduces the number of times the thread is created and destroyed. The ability to adjust the number of threads according to the system's endurance, so that the system can achieve the best performance.
thread pool principle:
There are multiple threads in a thread pool that are in a running state, and when you add an runnable or callable interface object to the thread pool,
There is a thread that executes the run () method or the call () method. If the method finishes executing, the thread does not terminate,
Instead, it continues to be in a running state in the pool to run the new task.
Understanding Thread Pools (several common static methods for creating thread pools in Java)
In Java, the top-level interface of the thread pool is the Executors tool class under the Util.concurrent package , where many methods of manipulating the thread pool are defined.
Among the most commonly used thread pools are:
1. Create a single thread pool:
newsinglethreadexecutor (), create a thread pool with only one threads, which performs all tasks in the order in which they are submitted.
In the event of an abnormal interruption, the thread pool will re-establish a single thread instead of completing the subsequent work.
code example:
/** * Create a single thread pool * @return*/public Executorservice Singlethreadpool () { = executors.newsinglethreadexecutor (); return singlepool; }
2. Create a cacheable thread pool:
Newcachedthreadpool (), create an unlimited size, and only the thread pool, he will be based on the amount of task to open up and reduce memory space,
But the size of thread pool threads depends on the performance of the system or the capacity of the JVM
code example:
/** * Create a cacheable thread pool * @return*/public Executorservice Cachedthreadpool () { = executors.newcachedthreadpool (); return cachedpool; }
3. Create a thread pool with a fixed size:
Newfixedthreadpool (), creates a fixed-size thread pool, the task commits the thread until the thread size reaches the maximum allowable value,
The thread pool complements a new thread if it ends.
code example:
/** * Create a thread pool of fixed size * @return*/public Executorservice Fixedthreadpool () { = Executors.newfixedthreadpool (2); return fixedpool; }
4. Create a thread pool that can be timed and executed periodically
Newscheduledthreadpool (), create a thread pool that can be timed, periodically executed, with no size limit for this thread pool,
Implement periodic task scheduling.
code example:
New Scheduledthreadpoolexecutor (1);
To make it easier for you to understand and compare the differences, the following will integrate these common thread pools into one program,
code example:
PackageCom.xhj.thread;ImportJava.util.Scanner;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.ScheduledThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit;/*** Understanding and application of several common thread pools * *@authorXiehejun **/ Public classCreatethreadpoolsextendsThread {@Override Public voidrun () {System.out.println ("System time:" + system.currenttimemillis () + "thread:" + thread.currentthread (). GetName () + "Executing!! "); } /*** Create a thread pool with a single thread * *@return */ PublicExecutorservice Singlethreadpool () {Executorservice Singlepool=Executors.newsinglethreadexecutor (); returnSinglepool; } /*** Create a thread pool with fixed size * *@return */ PublicExecutorservice Fixedthreadpool () {Executorservice Fixedpool= Executors.newfixedthreadpool (3); returnFixedpool; } /*** Create a cacheable thread pool * *@return */ PublicExecutorservice Cachedthreadpool () {Executorservice Cachedpool=Executors.newcachedthreadpool (); returnCachedpool; } /*** Put the created threads into the thread pool and execute * *@paramPool*/ Public voidService (Executorservice pool) {//Creating ThreadsThread Thread1 =NewCreatethreadpools (); Thread thread2=NewCreatethreadpools (); Thread thread3=NewCreatethreadpools (); Thread Thread4=NewCreatethreadpools (); Thread Thread5=NewCreatethreadpools (); //threads into the thread pool and executesPool.execute (THREAD1); Pool.execute (THREAD2); Pool.execute (THREAD3); Pool.execute (THREAD4); Pool.execute (THREAD5); //Close the thread poolPool.shutdown (); } /*** Create a thread pool of unlimited size, available with timed and recurring services*/ Public voidScheduledthreadpool () {scheduledthreadpoolexecutor Scheduledpool=NewScheduledthreadpoolexecutor (1); Scheduledpool.scheduleatfixedrate (NewRunnable () {@Override Public voidrun () {System.out.println ("=======" +System.currenttimemillis ()+ "========="); } }, 1000, 5000, Timeunit.milliseconds); Scheduledpool.scheduleatfixedrate (NewRunnable () {@Override Public voidrun () {System.out.println (System.nanotime ()); } }, 1000, 2000, Timeunit.milliseconds); } Public Static voidMain (string[] args) {createthreadpools Creatthreadpool=NewCreatethreadpools (); Scanner SC=NewScanner (system.in); while(true) {System.out.println ("Select Create thread Pool: 1. Single thread thread pool; 2. Cache thread pool; 3. Fixed size thread pool; 4 periodic thread pool execution); inti =Sc.nextint (); Switch(i) { Case1: System.out.println ("-----Call the thread pool for single thread-----"); //calling the thread pool of a single threadCreatthreadpool.service (Creatthreadpool.singlethreadpool ()); Break; Case2: System.out.println ("-----Call the thread pool of cacheable threads-----"); //to invoke a thread pool that caches threadsCreatthreadpool.service (Creatthreadpool.cachedthreadpool ()); Break; Case3: System.out.println ("-----Call the thread pool for fixed-size threads-----"); //call thread pool for fixed-size threadsCreatthreadpool.service (Creatthreadpool.fixedthreadpool ()); Break; Case4: System.out.println ("-----Call the size of the thread pool that is unlimited, timed, and periodically executed-----"); //call thread pool for fixed-size threadsCreatthreadpool.scheduledthreadpool (); Break; } } }}
note: When the thread pool task finishes, be sure to remember to close the thread pool and execute the shutdown () method.