Thread Pool - ThreadPoolExecutor

*Flowchart reference blog: https://blog.csdn.net/u010723709/article/details/50372322

1. ThreadPoolExecutor construction

      The ThreadPoolExecutor class inherits the AbstractExecutorService class

       AbstractExecutorService class implements ExecutorService interface

      The ExecutorService class inherits the Executor class

Two, 4 construction methods in the ThreadPoolExecutor class

1).  public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue)

2). public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory)

3).public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler)

4). public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,

                              RejectedExecutionHandler handler)

Third, the parameter explanation of the constructor in the ThreadPoolExecutor class

1) .int corePoolSize [maximum number of core threads]

   a. When creating a new thread in the thread pool, it will first compare whether it is greater than the number of core threads. If it is less than the number of core threads, it will create the number of non-core threads. If it is greater than the number of non-core threads, the number of core threads can be set by setting allowCoreThreadTimeOut=true, long keepAliveTime =time [timeout time] to destroy idle core threads. If this value is not set, it will always exist in the thread pool.

2) .int maximumPoolSize [the maximum value of the total number of threads, that is, the number of core threads + the number of non-core threads]

3) .long keepAliveTime [non-core thread idle timeout time]

   a. When a non-core thread is idle for more than keepAliveTime, the thread is destroyed. When controlling the core thread, the value of allowCoreThreadTimeOut needs to be set to true at the same time.

4). TimeUnit unit [unit of keepAliveTime, enumeration type]

NANOSECONDS: 1µmsec = 1µsec/1000MICROSECONDS: 1µsec = 1ms/1000MILLISECONDS: 1ms = 1sec/1000SECONDS: seconds MINUTES: minutes HOURS: hours DAYS: days

5). BlockingQueue<Runnable> workQueue [task queue of the thread pool]
a. When all core threads are not idle, the newly added tasks will be put into the queue for processing. If the queue is full, a non-core thread will be created to execute the task
b. Common type of
  workQueue ①.SynchronousQueue: After receiving the task, it is directly submitted to the thread for processing. If the thread is working, the thread is created directly. Because the thread can be created infinitely, the maximumPoolSize of the queue is specified as Integer.MZX_VALUE.
  ②.LinkedBlockingQueue: After receiving the task, determine whether the current thread is less than the number of core threads. If it is less, create a core thread to process the task. If the current number of threads is equal to the number of core threads, wait in the queue. The size of the queue defaults to Integer.MZX_VALUE, you can manually set the size of the queue, that is [public LinkedBlockingQueue(int capacity)]
  ③.ArrayBlockingQueue: You can limit the length of the queue, if the current number of threads is less than the number of core threads, create core threads for processing If the current number of threads reaches the number of core threads, it will be placed in the queue to wait. If the queue is full, a non-core thread will be created to process the task. If the current total number of threads is equal to maximumPoolSize and the queue is full, an error will occur.
  ④.DelayQueue: The elements in the queue must implement the Delayed interface. When the queue receives a task, it first enters the queue. Only when the specified delay time is reached, the task will be executed.

6) .ThreadFactory threadFactory [the way to create threads, generally not used]

7) .RejectedExecutionHandler handler [exception thrown, generally not used]

Fourth, submit the task

 Add a task to the thread pool through the ThreadPoolExecutor.execute(Runnable command) method

Five, ThreadPoolExecutor processing task strategy summary

  1. When the current number of threads is less than the number of core threads, create the number of core threads to process tasks
  2. When the number of current threads is equal to the number of core threads, put them in the waiting queue
  3. When the waiting queue is full, create non-core threads to process tasks
  4. When the queue is full and the total number of threads = maximumPoolSize, an exception is thrown by the RejectedExecutionHandler

Six, four common thread pools

   Java provides four thread pools through Executors. These four thread pools are implemented by directly or indirectly configuring the parameters of ThreadPoolExecutor
 
 (1) CachedThreadPool() [cacheable thread pool]
 
          1. Creation method
               ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
          2. Source code
              public static ExecutorService newCachedThreadPool() {
                    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                             60L, TimeUnit.SECONDS,
                                              new SynchronousQueue<Runnable>());
            }
          3 , Summary
           1) Unlimited number of threads
           2) If there are idle threads, then reuse idle threads, if there are no idle threads, create new threads
         
 (2) newFixedThreadPool() [fixed-length thread pool]
 
          1. Creation method
                ExecutorService fixed = Executors.newFixedThreadPool(int nThreads);
          2. Source code
              public static ExecutorService newFixedThreadPool(int nThreads) {
                    return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
            }
          3. Summary
               1), the maximum concurrent number of controllable threads (the number of concurrently executed threads)
               2), the excess threads will wait in the queue
          
 (3) newScheduledThreadPool() [supports timing and periodic task execution]
 
          1. Creation method
               ExecutorService scheduledPool = Executors.newScheduledThreadPool(int corePoolSize);
          2. Source code
               public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
                    return new ScheduledThreadPoolExecutor(corePoolSize);
              }

             public ScheduledThreadPoolExecutor(int corePoolSize) {
                         super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
                                     new DelayedWorkQueue());
            }
     
         3. Usage
                3.1. Delayed execution function [execute Runnable task with a delay of 3 seconds]
                       scheduledPool.schedule(Runnable,3,TimeUnit.SENCONDS);
                3.2. Cyclic execution function [cycle execution of tasks, first delay execution for 3 seconds, and cycle once every hour]
                        scheduledPool.schedule(Runnable,3,1,TimeUnit.HOURS);
        
 (4) newSingleThreadExecutor() [single-threaded thread pool]
 
          1. Creation method
                ExecutorService singlePool = Executors.newSingleThreadExecutor();
          2. Source code
              public static ExecutorService newSingleThreadExecutor() {
                            return new FinalizableDelegatedExecutorService
                                    (new ThreadPoolExecutor(1, 1,
                                            0L, TimeUnit.MILLISECONDS,
                                            new LinkedBlockingQueue<Runnable>()));
            }
          3. Summary
              1), there is only one worker thread to execute tasks
              2), all tasks are executed in the specified order, that is, follow the queue entry and exit rules
             
*Reference: https://www.jianshu.com/p/ 210eab345423
  





   



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325647299&siteId=291194637