Thread Pool (Java. util. Concurrent. threadpoolexecut
6. Recommendation
With the contribution of Doug Lea, A multithreading master, many concurrent features are added to jdk1.5, such as the thread pool.
I. Introduction
The thread pool class is Java. util. Concurrent. threadpoolexecutor. The common constructor is as follows:
Threadpoolexecutor (INT corepoolsize, int maximumpoolsize,
Long KeepAliveTime, timeunit unit,
Blockingqueue <runnable> workqueue,
Rejectedexecutionhandler handler)
Corepoolsize: Minimum number of threads maintained by the thread pool
Maximumpoolsize: Maximum number of threads maintained by the thread pool
KeepAliveTime: the idle time allowed by the thread pool to maintain the thread
Unit: the unit of idle time allowed by the thread pool maintenance thread.
Workqueue: The Buffer Queue used by the thread pool.
Handler: processing policy of the thread pool to reject tasks
A task is added to the thread pool using the execute (runnable) method. A task is a runnable object. The execution method of a task is the run () method of a runnable object.
When a task is added to the thread pool through the execute (runnable) method:
If the number of threads in the thread pool is smaller than corepoolsize, a new thread should be created to process the added tasks even if all threads in the thread pool are idle.
If the number in the thread pool is equal to corepoolsize, but the Buffer Queue workqueue is not full, the task is put into the buffer queue.
If the number in the thread pool is greater than corepoolsize, the Buffer Queue workqueue is full, and the number in the thread pool is smaller than maximumpoolsize, a new thread is created to process the added task.
If the number in the thread pool is greater than corepoolsize, the Buffer Queue workqueue is full, and the number in the thread pool is equal to maximumpoolsize, the handler policy is used to process the task.
That is, the priority of the processing task is:
Core Thread corepoolsize, task queue workqueue, and maximumpoolsize. If all three are full, handler is used to process the rejected task.
When the number of threads in the thread pool is greater than corepoolsize, if the idle time of a thread exceeds KeepAliveTime, the thread will be terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.
The optional parameters of unit are several static attributes in Java. util. Concurrent. timeunit:
Nanoseconds, microseconds, milliseconds, and seconds.
Workqueue I often use: Java. util. Concurrent. arrayblockingqueue
Handler has four options:
Threadpoolexecutor. abortpolicy ()
Throw a java. util. Concurrent. rejectedexecutionexception
Threadpoolexecutor. callerrunspolicy ()
Retry adding the current task and it will automatically call the execute () method again
Threadpoolexecutor. discardoldestpolicy ()
Discard Old tasks
Threadpoolexecutor. discardpolicy ()
Discard current task
II. General usage examples
//------------------------------------------------------------
// Testthreadpool. Java
// Package cn.simplelife.exe rcise;
Import java. Io. serializable;
Import java. util. Concurrent. arrayblockingqueue;
Import java. util. Concurrent. threadpoolexecutor;
Import java. util. Concurrent. timeunit;
Public class testthreadpool {
Private Static int producetasksleeptime = 2;
Private Static int consusk sleeptime = 2000;
Private Static int producetaskmaxnumber = 10;
Public static void main (string [] ARGs ){
// Construct a thread pool
Threadpoolexecutor threadpool = new threadpoolexecutor (2, 4, 3,
Timeunit. Seconds, new arrayblockingqueue <runnable> (3 ),
New threadpoolexecutor. discardoldestpolicy ());
For (INT I = 1; I <= producetaskmaxnumber; I ++ ){
Try {
// Generate a task and add it to the thread pool
String task = "task @" + I;
System. Out. println ("put" + task );
Threadpool.exe cute (New threadpooltask (task ));
// Easy to observe and wait for a while
Thread. Sleep (producetasksleeptime );
} Catch (exception e ){
E. printstacktrace ();
}
}
}
/**
* Tasks executed by the thread pool
* @ Author hdpan
*/
Public static class threadpooltask implements runnable, serializable {
Private Static final long serialversionuid = 0;
// Save the data required by the task
Private object threadpooltaskdata;
Threadpooltask (Object tasks ){
This. threadpooltaskdata = tasks;
}
Public void run (){
// Process a task. The processing method here is too simple, just a print statement
System. Out. println ("start..." + threadpooltaskdata );
Try {
//// Easy to observe and wait for a while
Thread. Sleep (consusksleeptime );
} Catch (exception e ){
E. printstacktrace ();
}
Threadpooltaskdata = NULL;
}
Public object gettask (){
Return this. threadpooltaskdata;
}
}
}
//------------------------------------------------------------
Note:
1. In this program, a task is a runnable object, that is, a threadpooltask object.
2. Generally, in addition to the processing method, the data to be processed is transmitted to the task through the constructor.
3. In this program, the main () method is equivalent to a cruel leader who sends out many tasks and throws them to a group named threadpool.
There are at least two members in this group. If the two are too busy, the task will be put into the task list.
If there are too many tasks in the backlog and no more than three tasks can be installed in the task list, hire new players to help. However, for cost-based consideration, you cannot hire too many players. You can only hire up to four players.
If the four players are busy and there are new tasks, the team will not be able to handle them, and the tasks will be handled through a strategy. Our approach is to keep distributing the tasks, until you accept this task (more cruel! Haha ).
Because it is costly for a team member to work. If the team member is idle and no new tasks are available for the 3seconds instance, some Members will be dismissed. However, for the normal operation of the group, even if you are idle, the team members cannot be less than two.
4. Adjust the size of producetasksleeptime and consusksleeptime to control the speed of dispatching and processing tasks. By changing these two values, you can observe the program working conditions at different rates.
5. Adjust the data in table 4, add the task discard policy, and change to the other three policies to see the different processing methods under different policies.
6. For other usage methods, see the help of JDK, which is easy to understand and use.