A brief introduction to thread pool _java in Java programming

Source: Internet
Author: User

Starting with Java 5, Java provides its own thread pool. A thread pool is a container of threads that only perform the rated number of threads at a time. Java.util.concurrent.ThreadPoolExecutor is such a thread pool. It is very flexible, but it is also more complex to use, this article will make an introduction to it.

The first is the constructor. Take the simplest constructor as an example:

Public threadpoolexecutor ( 
      int corepoolsize, 
      int maximumpoolsize, 
      long KeepAliveTime, 
      timeunit unit , 
      blockingqueue<runnable> Workqueue) 

It looks very complicated. here to introduce.
Corepoolsize refers to the size of the reserved thread pool.
Maximumpoolsize refers to the maximum size of the thread pool.
KeepAliveTime refers to the timeout for the end of an idle thread.
Unit is an enumeration that represents the units of a keepalivetime.
Workqueue represents the queue that holds the task.
We can understand the meaning of these parameters from the thread pool's working process. The thread pool works as follows:

1, when the line Chengchigang is created, there is not a thread inside. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool will not execute them immediately.
2, when the Execute () method is invoked to add a task, the thread pool makes the following judgment:
    A. If the number of threads running is less than corepoolsize, Then immediately create a thread to run this task;
    B. If the number of threads running is greater than or equal to corepoolsize, put this task in the queue.
    c. If the queue is full and the number of threads running is less than maximumpoolsize, create a thread to run the task;
    D. If the queue is full, and the number of threads running is greater than or equal to maximumpoolsize, the thread pool throws an exception telling the caller, "I can't accept a task anymore."
3, when a thread finishes a task, it takes the next task from the queue to execute.
4, when a thread has nothing to do, more than a certain amount of time (KeepAliveTime), the thread pool will judge if the current number of threads running is greater than corepoolsize, then the thread is stopped. So when all the tasks of the thread pool are complete, it eventually shrinks to the size of the corepoolsize.
This procedure explains that you don't have to join a task to be sure to do it first. Assuming that the queue size is 10,corepoolsize to 3,maximumpoolsize 6, then when 20 tasks are added, the order of execution is as follows: first perform tasks 1, 2, 3, and then the task 4~13 is placed in the queue. When the queue is full, tasks 14, 15, 16 are executed immediately, and the task 17~20 throws an exception. The final order is: 1, 2, 3, 14, 15, 16, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13. The following is an example of a thread pool usage:

 public static void main (string[) args) {blockingqueue<runnable> queue = new Li 
  Nkedblockingqueue<runnable> (); 
  Threadpoolexecutor executor = new Threadpoolexecutor (3, 6, 1, timeunit.days, queue); 
          for (int i = 0; i < i++) {executor.execute, new Runnable () {public void run () {try { 
        Thread.Sleep (1000); 
        catch (Interruptedexception e) {e.printstacktrace (); 
      } System.out.println (String.Format ("Thread%d finished", This.hashcode ())); 
} executor.shutdown (); } 

A description of this example is as follows:

1, Blockingqueue is only an interface, commonly used to implement classes have Linkedblockingqueue and Arrayblockingqueue. The advantage of using linkedblockingqueue is that there is no size limit. In this case, execute () does not throw an exception because the queue is not full, and the number of threads running in the thread pool will never exceed the corepoolsize, and KeepAliveTime parameters are meaningless.

2, Shutdown () method will not block. Once the shutdown () method is invoked, the main thread ends immediately, and the thread pool continues to run until all the tasks have finished executing. If you do not invoke the shutdown () method, the thread pool will persist so that new tasks are added at any time.

Here is a small part of the thread pool. Threadpoolexecutor is highly scalable, but the premise of extending it is to be familiar with how it works. The following article will explain how to extend the Threadpoolexecutor class.

The Ava.util.concurrent.ThreadPoolExecutor class provides rich scalability. You can customize its behavior by creating subclasses of it. For example, I want to print a message after each task ends, but I can't modify the Task object, so I can write:

Threadpoolexecutor executor = new Threadpoolexecutor (size, maxSize, 1, timeunit.days, queue) {
  protected void AfterExecute (Runnable R, Throwable t) {
    System.out.println ("Task finished.");

In addition to the AfterExecute method, the Threadpoolexecutor class also has BeforeExecute () and terminated () methods that can be overridden to execute before the task executes and after the entire thread pool is stopped.

In addition to the actions that can be added before and after a task is executed, Threadpoolexecutor also allows you to customize the execution strategy when the task fails to add. You can invoke the Setrejectedexecutionhandler () method of the thread pool to replace the existing policy with a custom Rejectedexecutionhandler object. Threadpoolexecutor offers 4 existing strategies, respectively:
Threadpoolexecutor.abortpolicy: Indicates a reject task and throws an exception
Threadpoolexecutor.discardpolicy: rejects the task but does not do any action
Threadpoolexecutor.callerrunspolicy: Represents a reject task and executes it directly in the caller's thread
Threadpoolexecutor.discardoldestpolicy: Indicates that the first task in the task queue is discarded first, and then the task is added to the queue.
Here is an example:
Threadpoolexecutor executor = new Threadpoolexecutor (size, maxSize, 1, timeunit.days, queue);
Executor.setrejectedexecutionhandler (New Threadpoolexecutor.discardpolicy ());

In addition, you can write your own strategy by implementing the Rejectedexecutionhandler interface. Here is an example:

Threadpoolexecutor executor = new Threadpoolexecutor (3, 6, 1, timeunit.seconds, queue,
    new Rejectedexecutionhandler () {public
      void Rejectedexecution (Runnable R, Threadpoolexecutor executor) {
        System.out.println ( String.Format ("Task%d rejected.", R.hashcode ());

Related Article

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.