Java Multithreading (quad)-Custom thread pool

Source: Internet
Author: User

When we use the thread pool, we can use methods such as Newcachedthreadpool () or newfixedthreadpool (int), in fact, we go deep into these methods, we can see that their implementation is the way.

 1  public  static           Executorservice Newcachedthreadpool () { 2  return  new  Threadpoolexecutor (0 3  60l 4  new  Synchronousqueue<runn Able> ());  5 } 
1    Public Static Executorservice newfixedthreadpool (int  nthreads) {2         returnnew Threadpoolexecutor (Nthreads, Nthreads,3                                       0L, Timeunit.milliseconds,4                                        New linkedblockingqueue<runnable>()); 5  }

There are several different types of thread pools that are created by the core class Threadpoolexecutor, and if we are going to customize the thread pool, it is done by this class.

This class has four construction methods, look at the source code can be seen, the first three construction methods, is actually called the fourth construction method, so we explain the fourth constructor method of the parameter meaning.

 Public Threadpoolexecutor (int  corepoolsize,                              int  maximumpoolsize,                              Long  KeepAliveTime,                              timeunit unit,                              blockingqueue<Runnable> workQueue,                              Threadfactory threadfactory,                              rejectedexecutionhandler handler)

Corepoolsize: The size of the core thread pool, after the online pool is created, there is no thread in it. (Of course, calling the Prestartallcorethreads () or Prestartcorethread () method will pre-create the thread without waiting for the task to arrive). Threads are created when a task comes in. When the number of threads in the thread pool reaches corepoolsize, the task is placed in the cache queue. (that is, workQueue).

Maximumpoolsize: What is the maximum number of threads? It marks the maximum number of threads for this thread pool. If there is no maximum number, when the number of threads created reaches a certain limit, the last memory must be blown out.
KeepAliveTime: When a thread does not have a task, the maximum amount of time that is kept is terminated beyond that time. By default, the KeepAliveTime value will only work if the thread pool has more threads than corepoolsize. Also say that only the number of thread pool threads exceeds corepoolsize. We will stop the idle thread that has timed out. Otherwise, you can keep the thread pool in a corepoolsize thread.


Unit: The time unit of the parameter KeepAliveTime, which is a few properties of the Timeunit class.
Such as:

WorkQueue: The queue used to store the task to be executed, different thread pool its implementation of the queue is different (because this is related to queuing policy issues) such as the following several
Arrayblockingqueue: array-based queues that need to be sized when created.
Linkedblockingqueue: Linked list-based queue, if no size is specified, the default value is Integer.max_value. (This is the queue used by Newfixedthreadpool and Newsinglethreadexecutor).
Synchronousqueue: This kind of queue is special because it does not queue up and creates a new thread to commit the task directly. (This is the queue used by Newcachedthreadpool).

Threadfactory: Thread factory, used to create threads.

Handler: When you reject a task, you generally have the following four strategies,
(1) Threadpoolexecutor.abortpolicy discards the task and throws a rejectedexecutionexception exception.
(2) Threadpoolexecutor.callerrunspolicy: The task is rejected by the thread pool and executed by the threads calling the Execute method.
(3) Threadpoolexecutor.discardoldestpolicy: Discard the previous task in the queue and retry the task.
(4) Threadpoolexecutor.discardpolicy, discards the task, but does not throw an exception.

Look at a demo, sample code address: Src/thread_runnable/customthreadpool.java

1 classCustomTaskImplementsrunnable{2     Private  intID;3      PublicCustomTask (intID) {4          This. ID =ID;5     }6 7 @Override8      Public voidrun () {9         //TODO auto-generated Method StubTenSystem.out.println ("#" + ID + "threadid=" +Thread.CurrentThread (). GetName ()); One         Try { ATimeUnit.MILLISECONDS.sleep (100); -}Catch(interruptedexception e) { - e.printstacktrace (); the         } -     } -      - } +  -  Public classCustomthreadpool { +      Public Static voidMain (string[] args) { A         //TODO auto-generated Method Stub atblockingqueue<runnable> queue =NewArrayblockingqueue<> (10); -Threadpoolexecutor pool =NewThreadpoolexecutor (3, 5, 60, timeunit.microseconds, queue); -              -              for(inti=0; i<7; i++){ -Runnable task =NewCustomTask (i); - Pool.execute (Task); in             } -              to Pool.shutdown (); +     } -  the}


Output Result:

From this example, it can be seen that although we have 7 tasks, in fact, only three threads are running.
So what is the processing strategy when we submit the task to the thread pool?

(1) If the number of threads in the current thread pool is less than corepoolsize (the core pool is not yet full), create a new thread to process the task.
(2) If the core pool is full, a new task will be added to the task queue and, if successful, wait for the idle thread to pull it out of the queue and execute it, and if the queue is full, continue to the next step.
(3), at this point, if the number of thread pool threads is less than maximumpoolsize, then create a new thread to perform the task, otherwise, it means that the thread pool to the maximum saturation capacity, no way to deal with, at this time, according to the rejection policy to deal with. (That is, the handler object in the constructor).

(4) If the thread pool's number of threads is greater than corepoolsize, when a thread's idle time exceeds KeepAliveTime, the thread will be destroyed until the thread number of threads is not greater than corepoolsize.

To give an easy-to-understand example, the company will set up a project team to handle certain tasks, and the staffing of the HR Department is 10 people (corepoolsize). At the same time they set up a special office with 15 seats (maximumpoolsize). At the very beginning of a task, recruit a person. In this way, a recruit, recruit 10 people, constantly have a new task to the project team, everyone is constantly working on the task. But then more and more tasks, 10 people can not finish. The rest of the task was to be lined up outside the corridor. Later the task was more and more, and the queue in the corridor was crowded. Then had to find some temporary workers to help complete the task. Because the office has only 15 seats, they can only find 5 temporary workers at most. But the task is still more and more, the basic treatment is not finished, that no way, the project group had to refuse to take new tasks. (The way of Refusal is Handler), the final task gradually less, everyone is more relaxed. So decided to look at everyone's performance, who behaved badly, who was cleared out of the office (more than KeepAliveTime), until the office only 10 people (corepoolsize), maintain a fixed staffing until the establishment.


With regard to the thread pool, Threadpoolexecutor also provides some methods to be aware of:

(1) Shutdown (), smooth close thread pool. (If you have unfinished tasks, wait for them to finish).
(2) Shutdownnow (). A simple brute-off thread pool. (tasks that are not completed are also closed directly).
(3) Setcorepoolsize (). Sets/changes the size of the core pool.
(4) Setmaximumpoolsize (), Sets/changes the limit of the maximum number of threads in the thread pool.

Java Multithreading (quad)-Custom thread pool

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.