There are two ways to implement the thread pool, one is self-implementation, and the other is to use the built-in executorservice class.
I. First, implement it on your own. The main knowledge point is thread wake-up and sleep, and directly go to the Code:
First, define an abstract task that contains the run method. The specific task execution must inherit this class.
public abstract class TaskRunnable {public abstract void run();}
The main core threadmanager of thread pool management is as follows:
Public class threadpoolmanager {Private Static threadpoolmanager instance = NULL; private final list <taskrunnable> taskqueue = collections. synchronizedlist (new worker list <taskrunnable> (); // task queue private final workthread [] workthreads; // working thread (the thread that actually executes the task) private Static final int default_worker_num = 5; // Number of worker threads (the default number of worker threads is 5) Private threadpoolmanager () {This (default_worker_num);} private threadpool Manager (INT num) {workthreads = new workthread [num]; for (INT I = 0; I <num; I ++) {workthreads [I] = new workthread (I) ;}} public static synchronized threadpoolmanager getinstance () {If (null = instance) {instance = new threadpoolmanager ();} return instance;} public void addtask (taskrunnable task) {// lock synchronized (taskqueue) {If (null! = Task) {taskqueue. add (task); taskqueue. policyall () ;}} public void batchaddtask (taskrunnable [] tasks) {// You must lock synchronized (taskqueue) {for (taskrunnable E: tasks) to modify the task queue) {If (null! = E) {taskqueue. add (E); taskqueue. policyall () ;}}} public void destory () {system. out. println ("pool begins to destory... "); For (INT I = 0; I <workthreads. length; I ++) {workthread current = workthreads [I]; If (null! = Current) {try {current. stopthread ();} catch (exception e) {e. printstacktrace () ;}} workthreads [I] = NULL;} // lock synchronized (taskqueue) {taskqueue for operations on the task queue. clear ();} system. out. println ("pool ends to destory... ");} private class workthread extends thread {private Boolean isruning = true; private Boolean iswaiting = false; Public workthread (INT taskid) {This. start ();} public Boolean iswaiti Ng () {return iswaiting;} // If the thread cannot be terminated immediately when the task is in progress, exit run () when the isruning is detected to be false after the task is completed () method public void stopthread () {isruning = false;} @ override public void run () {While (isruning) {taskrunnable temp = NULL; // synchronized (taskqueue) should be locked for operations on the task queue {// The task queue is empty, waiting for the new task to join the while (isruning & taskqueue. isempty () {try {taskqueue. wait (20);} catch (interruptedexception e) {system. out. println ("interruptedex Ception occre... "); E. printstacktrace () ;}} if (isruning) {temp = taskqueue. remove (0) ;}// when a new task is waiting to be added, terminate the thread (call the stopthread function) to cause temp = NULL if (temp! = NULL) {iswaiting = false; temp. Run (); iswaiting = true ;}}}}}
Related instance project: http://download.csdn.net/detail/hustpzb/4957783
2. executorservice
It is much easier to create a thread pool. developers can easily create their own thread pools.
(1)Use the default thread factory of executor to create a thread
To create a thread pool, follow these steps:
| 1. Define thread classes |
Class handler implements runnable {
} |
| 2. Create an executorservice Thread Pool |
Executorservice = executors. newcachedthreadpool ();
Or
Int cpunums = runtime. getruntime (). availableprocessors (); // obtain the number of CPUs of the current system
Executorservice = executors. newfixedthreadpool (cpunums * pool_size); // executorservice generally flexibly defines the thread pool size based on system resources |
| 3. Call the thread pool operation |
Loop operation to become a daemon and put the new instance into the executor pool
While (true ){
Executorservice.exe cute (new handler (socket ));
// Class handler implements runnable {
Or
Executorservice.exe cute (createtask (I ));
// Private Static runnable createtask (final int taskid)
}
Execute (runnable object) Method
Actually, the START () method is called for the runnable object.
(Of course there are some other background actions, such as queue, priority, idle timeout, and active activation) |
In the above section, we use newfixedthreadpool to create a thread pool, but there are other methods to create it. Let's take a look at the differences between other executorservice thread pool objects.
| 1. newcachedthreadpool () |
-Cache pool, first check whether there are any threads in the pool that have been previously established. If yes, reuse it. If not, create a new thread to join the pool.
-Cache pools are usually used to execute asynchronous tasks with short lifetime.
Therefore, some connection-oriented daemon-type servers are rarely used.
-The Reuse thread must be a thread in the pool of timeout idle. The default timeout value is 60 s. If the idle length is exceeded, the thread instance will be terminated and removed from the pool.
Note: The thread placed in the cachedthreadpool does not have to worry about its termination. If it exceeds the timeout, it is automatically terminated. |
| 2. newfixedthreadpool |
-The newfixedthreadpool is similar to the cachethreadpool and can be used for reuse, but cannot be used to create new threads at any time.
-Its uniqueness: at any time point, only a fixed number of active threads can exist. If a new thread needs to be created, it can only be placed in another queue for waiting, until the termination of a thread in the current thread is directly removed from the pool
-Unlike cachethreadpool, fixedthreadpool does not have an idle mechanism (it may also exist, but since the document is not mentioned, it must be very long, such as relying on the upper layer's TCP or UDP idle mechanism ), therefore, most fixedthreadpool targets some very stable and fixed regular concurrent threads, which are mostly used on servers.
-From the source code of the method, the cache pool and fixed pool call the same underlying pool, except that the parameters are different: The number of threads in the fixed pool is fixed, and the value is 0 seconds idle (no idle)
The number of threads in the cache pool supports 0-integer.max_value (obviously, the host's resource capacity is not fully considered), and the idle is 60 seconds. |
| 3. scheduledthreadpool |
-Scheduling Thread Pool
-The threads in this pool can be delay in sequence by schedule or periodical. |
| 4. singlethreadexecutor |
-Singleton thread. There can only be one thread in any time pool
-It uses the same underlying pool as the cache pool and fixed pool, but the number of threads is 1-seconds (no idle) |
(2) define your own thread factory separately
The following is the default thread factory code:
Static class defaultthreadfactory implements threadfactory {
Static final atomicinteger poolnumber = new atomicinteger (1 );
Final threadgroup group;
Final atomicinteger threadnumber = new atomicinteger (1 );
Final string nameprefix;
Defaultthreadfactory (){
Securitymanager S = system. getsecuritymanager ();
Group = (s! = NULL )? S. getthreadgroup (): thread. currentthread (). getthreadgroup ();
Nameprefix = "pool-" + poolnumber. getandincrement () + "-thread -";
}
Public thread newthread (runnable R ){
Thread t = new thread (group, R, nameprefix + threadnumber. getandincrement (), 0 );
If (T. isdaemon ())
T. setdaemon (false );
If (T. getpriority ()! = Thread. norm_priority)
T. setpriority (thread. norm_priority );
Return T;
}
} |
You can also customize threadfactory and add it to the pool creation parameters.
| Public static executorservice newcachedthreadpool (threadfactory ){ |
Execute () method of executor
The execute () method adds the runnable instance to the pool and performs some pool size calculation and priority processing.
The execute () method itself is defined in the executor interface. Multiple implementation Classes define different execute () methods.
For example, the execute method of the threadpoolexecutor class (cache, fiexed, and single pools are called) is as follows:
Public void execute (runnable command ){
If (command = NULL)
Throw new nullpointerexception ();
If (poolsize> = corepoolsize |! Addifundercorepoolsize (command )){
If (runstate = running & workqueue. Offer (command )){
If (runstate! = Running | poolsize = 0)
Ensurequeuedtaskhandled (command );
}
Else if (! AddifundermaximumpoolsizE (command ))
Reject (command); // is shutdown or saturated
} |