Most of the text is transferred from http://www.cnblogs.com/yydcdut/p/3890893.html
1.Java Thread Pool Fundamentals
The basic principle of the thread pool is that the system starts a number of threads and makes them sleep, and when there is a new task, it wakes up one of the sleep threads in the thread pool and lets it handle the task. When the task is finished, the thread is asleep again.
In Java, the main component of the thread pool is the worker thread, which is independent of the runnable and callable tasks it performs, and is often used to perform multiple tasks.
The difference between a worker thread and a normal thread is different from the Run method. After the normal thread completes the code that the thread should execute, the thread ends, the Java virtual Machine reclaims the resources allocated to the thread, and the thread object is reclaimed by the garbage collection period. The worker thread that makes up the thread pool is a reusable thread whose run method executes the specific code of a task and puts itself into sleep instead of ending the thread.
2. The role of the thread pool
The thread pool function is to limit the number of threads executing in the system.
According to the environment of the system, the number of threads can be set automatically or manually to achieve the best performance; less waste of system resources, more caused by the system congestion efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue is executed. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.
3. Why Use Threads
① reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
② can adjust the number of threads in the thread pool according to the ability of the system, prevent the server from being exhausted because it consumes too much memory (approximately 1MB of memory per thread, the more threads open, the more memory is consumed and the last crashes).
Several important classes in the 4.Concurrent package
The top interface of the thread pool in Java is executor, but strictly speaking, executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice.
Some of the more important classes:
| Executorservice |
A true thread pool interface |
| Scheduledexecutorservice |
Similar to Timer/timertask to solve problems that require repetitive task execution |
| Threadpoolexecutor |
Default implementation of Executorservice |
| Scheduledthreadpoolexecutor |
Implementation of Scheduledexecutorservice interface for inheriting threadpoolexecutor, and class implementation of periodic task scheduling |
the frame diagram between classes
Threadpoolexecutor detailed
The signature of the complete construction method for Hreadpoolexecutor is:
Threadpoolexecutor (int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue<runnable > WorkQueue, threadfactory threadfactory, Rejectedexecutionhandler handler).
Parameter explanation:
corepoolsize -The number of threads that are saved in the pool, including idle threads.
maximumpoolsize-The maximum number of threads allowed in the pool.
KeepAliveTime -When the number of threads is greater than the core, this is the maximum time to wait for a new task before terminating the extra idle thread.
Unit-the time units of the KeepAliveTime parameter.
WorkQueue -the queue used to hold the task before execution. This queue keeps only the runnable tasks that are submitted by the Execute method.
Threadfactory -The factory that the executor uses when it creates a new thread.
Handler -the handler that is used when execution is blocked because the thread range and queue capacity are exceeded.
Threadpoolexecutor is the underlying implementation of the Executors class.
In the JDK help documentation, there is a passage:
"It is highly recommended that programmers use the more convenient executors factory method Executors.newcachedthreadpool () (without a boundary pool, which can be recycled by automatic thread), Executors.newfixedthreadpool (int) (fixed-size thread pool) executors.newsinglethreadexecutor () (a single background thread) that has predefined settings for most usage scenarios. ”
Here are a few classes of source code:
Executorservice newfixedthreadpool (int nthreads): Fixed size thread pool
public static Executorservice newfixedthreadpool (int nthreads) { return new Threadpoolexecutor (Nthreads, Nthreads, 0L, Timeunit.milliseconds, New linkedblockingqueue<runnable> ()); }
As you can see, the size of the corepoolsize and Maximumpoolsize is the same (in fact, the maximumpoolsize parameter is meaningless if you use the unbounded queue), What is the value table name for KeepAliveTime and unit? -That's the realization don't want to keep alive! The last Blockingqueue chose Linkedblockingqueue, the linkedblockingqueue has a characteristic, it is unbounded .
Executorservice Newsinglethreadexecutor (): Single thread
public static Executorservice Newsinglethreadexecutor () { return new Finalizabledelegatedexecutorservice ( New Threadpoolexecutor (1, 1, 0L, Timeunit.milliseconds, new Linkedblockingqueue<runnable> ())); }
Executorservice Newcachedthreadpool (): No boundary pool, automatic thread recovery
public static Executorservice Newcachedthreadpool () { return new Threadpoolexecutor (0, Integer.max_value, 60L , Timeunit.seconds, new synchronousqueue<runnable> ()); }
The first is the unbounded thread pool, so we can find maximumpoolsize as Integer.max_value. followed by the blockingqueue of the choice to useSynchronousqueue。 May be a little strange for the blockingqueue, simply said: In the Blockingqueue, each insert operation must wait for the corresponding removal of another thread.
Start with the blockingqueue<runnable> workQueue the first entry. In the JDK, it has been made clear that there are three types of queue.
All blockingqueue can be used to transfer and maintain submitted tasks. You can use this queue to interact with the pool size:
If you run fewer threads than corepoolsize, executor always prefers to add new threads without queuing. (if the currently running thread is less than corepoolsize, the task will not be stored at all, added to the queue, but directly to the guy (thread) to start running)
If you are running a thread that is equal to or more than corepoolsize, executor always prefers to join the request to the queue without adding a new thread .
If the request cannot be queued, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is rejected.
Three types of queue
There are three common strategies for queuing:
Submit directly
The default option for the work queue is synchronousqueue, which will submit tasks directly to the thread without maintaining them. Here, if there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be constructed. This policy avoids locking when processing a set of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows the possibility of an increase in the number of lines that are allowed to continue when the command arrives in a row that exceeds the average that the queue can handle.
Unbounded queue
Using unbounded queues (for example, linkedblockingqueue that do not have a predefined capacity) will cause all corepoolsize threads to be busy while the newer tasks are waiting in the queue. This way, the created thread will not exceed corepoolsize. (therefore, the value of the maximumpoolsize is not valid.) When each task is completely independent of other tasks, that is, when task execution does not affect each other, it is appropriate to use a unbounded queue, for example, in a Web page server. This queueing can be used to handle transient burst requests, which allow the possibility of an increase in the number of lines that are allowed to occur when the command reaches an average of more than the queue can handle.
bounded queues
When using limited maximumpoolsizes, bounded queues (such as Arrayblockingqueue) help prevent resource exhaustion , but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.
The choice of Blockingqueue
① uses a direct commit policy, which is also synchronousqueue
First of all, Synchronousqueue is unbounded, that is, the ability to save several tasks is unlimited, but because of the nature of the queue itself, you must wait for another thread to continue to add after you have added the element . Not the core thread here is the newly created thread, but let's just imagine the next scenario.
We use the parameters to construct the Threadpoolexecutor:
New Threadpoolexecutor ( 2, 3, Timeunit.seconds, new synchronousqueue<runnable> (), new Recorderthreadfactory ("Cookierecorderpool"), new Threadpoolexecutor.callerrunspolicy ());
When a core thread already has 2 running.
1. At this point, a task continues (a), according to the "if running thread equals or more than corepoolsize," executor always prefers to join the request to the queue.Without adding a new thread。 ", so a is added to the queue.
2, another task (B), and the Core 2 threads are not busy, OK, next first try to describe the 1, but because of the use of synchronousqueue, so must not be added.
3. At this point, the above mentioned "if the request cannot be joined to the queue, create a new thread, unless this thread is created beyond maximumpoolsize, in which case the task will be rejected." , so a new thread must be created to run the task.
4, temporarily also can, but if these three tasks are not completed, a series of two tasks, the first to add to the queue, the latter one? The queue cannot be inserted, and the number of threads reaches Maximumpoolsize, so you have to execute the exception policy.
so the use of synchronousqueue usually requires maximumpoolsize to be unbounded., so that this can be avoided (if you want to restrict the use of a bounded queue directly). It is well written in the JDK that uses synchronousqueue: This policy avoids locking when processing a set of requests that may have internal dependencies.
What do you mean? If your task A1,A2 has internal Association, A1 need to run first, then submit A1, and then submit A2, when using synchronousqueue we can guarantee that A1 must be executed first, before A1 is executed, A2 cannot add to the queue.
② uses the unbounded queue policy, which is linkedblockingqueue
This is the most complex use, so the JDK does not recommend the use of some reason. Compared with the above, the most important feature is to prevent the depletion of the situation occurs.
For example, consider the following construction method:
New Threadpoolexecutor ( 2, 4, Timeunit.seconds, new Arrayblockingqueue<runnable> (2), new Recorderthreadfactory ("Cookierecorderpool"), new Threadpoolexecutor.callerrunspolicy ());
Assume that all tasks are never done.
For the first, a, b to run directly, then, if the c,d, they will be placed in the queue, if the next e,f, then increase the thread run e,f. However, if you come back to the task, the queue is no longer acceptable, and the number of threads reaches the maximum limit, so a deny policy is used to handle it.
KeepAliveTime
The explanation in the JDK is that when the number of threads is greater than the core, this is the maximum amount of time that the extra idle thread waits for a new task before terminating.
A bit of a mouthful, in fact, this is not difficult to understand, in the use of "pool" in the application, most of them have similar parameters need to be configured. such as the database connection pool, the Maxidle,minidle parameter in DBCP.
What do you mean? Then the above explanation, and then sent to the boss of the workers are always "borrowed", as the saying goes, "There is still", but the problem here is when, if the borrowed workers just completed a task to return, and later found that the task is still, it is not to borrow? This one, the boss must have died.
Reasonable strategy: Since borrowed, then borrow more for a while. It was not until after "a certain period" that the workers could not be used again, and they could return. Some time here is the meaning of KeepAliveTime, Timeunit is the measure of KeepAliveTime value.
Rejectedexecutionhandler
In another case, even if the boss borrowed the workers, but the task continued to come, or not busy, then the whole team had to refuse to accept.
The Rejectedexecutionhandler interface provides the opportunity for a custom method to reject the processing of a task. The 4 policy is already included by default in Threadpoolexecutor because the source code is very simple and is posted directly here.
① callerrunspolicy: The thread invokes the execute itself that runs the task. This strategy provides a simple feedback control mechanism that can slow down the submission of new tasks.
public void Rejectedexecution (Runnable R, Threadpoolexecutor e) { if (!e.isshutdown ()) { r.run (); } }
This strategy obviously does not want to abandon the task. However, since there are no resources in the pool, it is executed directly using the thread itself that invoked the execute.
② abortpolicy: Handler rejection will throw runtime rejectedexecutionexception
public void Rejectedexecution (Runnable R, Threadpoolexecutor e) { throw new rejectedexecutionexception ();
This strategy throws an exception directly, discarding the task.
③ discardpolicy: The task that cannot be performed will be deleted
public void Rejectedexecution (Runnable R, Threadpoolexecutor e) { }
This strategy is almost as much a abortpolicy as a drop-off task, except that he does not throw an exception.
④ discardoldestpolicy: If the execution program has not been closed, the task that is in the head of the work queue is deleted, and then the execution of the program is retried (repeat this process if it fails again)
public void Rejectedexecution (Runnable R, Threadpoolexecutor e) { if (!e.isshutdown ()) { e.getqueue (). poll (); C2/>e.execute (R); } }
The strategy is a little more complicated, with the pool not shutting down and first losing the oldest task cached in the queue, and then trying to run the task again. This strategy requires proper care.
Imagine: If other threads are still running, then the new task kicks off the old task, slows down the queue, and a task kicks off the oldest task in the queue.
Summary
KeepAliveTime are related to the types of maximumpoolsize and Blockingqueue. If the blockingqueue is unbounded, then the maximumpoolsize will never be triggered, and the natural keepalivetime will have no meaning.
Conversely, if the number of cores is small, bounded blockingqueue values are smaller, and the KeepAliveTime is small, if the task is frequent, then the system will frequently apply for recycling threads.
5.Java Thread Pool Usage Example
①newsinglethreadexecutor
Mythread.java
public class MyThread extends Thread {@Overridepublic void run () {System.out.println (Thread.CurrentThread (). GetName () + "Executing ... ");}}
Testsinglethreadexecutor.java
public class Testsinglethreadexecutor {public static void main (string[] args) {//Create a thread pool of reusable fixed threads executorservice pool = E Xecutors.newsinglethreadexecutor ();//Create an object that implements the Runnable interface thread T1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread ();//place thread into pool execution Pool.execute (t1);p ool.execute (T2);p Ool.execute (T3);p ool.execute (T4); Pool.execute (T5);//close thread pool Pool.shutdown ();}}
Output Result:
Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ...
②newfixedthreadpool
Testfixedthreadpool.java
public class Testfixedthreadpool {public static void main (string[] args) {//Create a thread pool with a reusable fixed number of threads executorservice pool = execut Ors.newfixedthreadpool (5);//Create an object that implements the Runnable interface thread T1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread ();//place thread into pool execution Pool.execute (t1);p ool.execute (T2);p Ool.execute (T3);p ool.execute (T4); Pool.execute (T5);//close thread pool Pool.shutdown ();}}
Output Result:
Pool-1-thread-2 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-3 is executing ... Pool-1-thread-5 is executing ...
③newcachedthreadpool
Testcachedthreadpool.java
public class Testcachedthreadpool {public static void main (string[] args) {Executorservice pool = Executors.newcachedthre Adpool ();//Create an object that implements the Runnable interface thread T1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread T4 = new MyThread (); Thread T5 = new MyThread ();//place thread into pool execution Pool.execute (t1);p ool.execute (T2);p Ool.execute (T3);p ool.execute (T4); Pool.execute (T5);//close thread pool Pool.shutdown ();}}
Output Result:
Pool-1-thread-2 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-5 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-3 is executing ...
④newscheduledthreadpool
Testscheduledthreadpoolexecutor.java
public class Testscheduledthreadpoolexecutor {public static void main (string[] args) {Scheduledthreadpoolexecutor exec = New Scheduledthreadpoolexecutor, Exec.scheduleatfixedrate (New MyThread (), 0, timeunit.milliseconds);}