Android thread pool explain in simple terms (1)

Series Article Directory

The first chapter Android thread pool explain in simple language (1) The
second chapter Android thread pool explain in simple language (2)



Preface

In Android development, time-consuming tasks are often processed in non-UI threads. At this time, threads are needed to handle asynchronous tasks. If a thread is created every time and destroyed after execution, it will consume a lot of scenes that require multiple threads to use frequently. Loss of resources and performance. And threads are easy to do things independently, and it is difficult to control.

In order to solve the drawbacks of the use of threads, the Executor framework is provided in Java 1.5 to decouple the submission and execution of tasks. The submission of tasks is handed over to Runnable or Callable, and the Executor framework is used to process tasks. The core implementation class of the Executor framework is ThreadPoolExecutor


One, the meaning of thread pool

There are many concurrent threads in the program. If each manual creation is only performed for a short time and the task ends, then frequent creation and destruction of threads will reduce the efficiency of the system and reduce the efficiency of CPU usage. In order to save resources and improve efficiency, Java provides a thread pool to solve the problem.

The thread pool is actually a container that holds multiple threads. The threads can be used repeatedly, eliminating the need to create thread objects frequently, and there is no need to repeatedly create threads and consume too much resources.


Second, what are the advantages of thread pools

  1. Reduce the consumption of system resources and reduce the consumption caused by thread creation and destruction by reusing existing threads multiple times;
  2. Improve the response speed of the system. When a task arrives, it can be executed immediately without waiting for the creation of a new thread by reusing existing threads;
  3. Improve the manageability of threads, adjust the number of worker threads according to the carrying capacity of the system to prevent OOM from excessive memory usage (each thread consumes about 1MB). At the same time, there are too many threads, and frequent CPU switching will produce high amounts Scheduling time cost and reducing CPU scheduling fragment time. And you can use the thread pool to uniformly allocate, tune and monitor threads.
  4. Provide more powerful functions, delay timing thread pool.

Three, thread pool creation

The top-level interface of the thread pool in Java is java.util.concurrent.Executor, but in a strict sense, Executor is not a thread pool, but a tool for executing threads. The real thread pool interface java.util.concurrent.ExecutorService.

It is more complicated to configure a thread pool. If you are not very clear about the principle of the thread pool, it is very likely that the configured thread pool is not optimal, so it is provided in the java.util.concurrent.Executors thread factory class Some static factories generate some commonly used thread pools. The official recommendation is to use the Executors engineering class to create thread pool objects. Executors are tools and factory classes for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.

If ThreadPoolExecutor is created, Executors calls newFixedThreadPool, newSingleThreadExecutor, and newCachedThreadPool to create thread pools that are all of ThreadPoolExecutor type. No matter what kind of creation method of the Executors class is called, the constructor of the ThreadPoolExecutor class will eventually be called.
code show as below:

/**
 *
 * @param corePoolSize 保留在池中的线​​程数,即使*处于空闲状态,
 *                     除非设置了{@code allowCoreThreadTimeOut}
 * @param maximumPoolSize 池中允许的最大线程数
 * @param keepAliveTime 当线程数大于核心时,这是多余的空闲线程在终止之前等待新任务的最长时间。
 * @param unit {@code keepAliveTime}参数的时间单位
 * @param workQueue 在执行任务之前用于保留任务的队列。该队列将仅保存由{@code execute}方法提交的{@code Runnable} *任务。
 * @param threadFactory 执行程序创建新线程时要使用的工厂
 * @param handler 当执行被阻塞时要使用的处理程序,因为达到了线程界限和队列容量,注意它并不是一个我们常见的Handler
 * @throws IllegalArgumentException 如果满足下列条件之一,则报IllegalArgumentException异常:
 *         {@code corePoolSize < 0}<br>
 *         {@code keepAliveTime < 0}<br>
 *         {@code maximumPoolSize <= 0}<br>
 *         {@code maximumPoolSize < corePoolSize}
 * @throws NullPointerException  如果 workQueue、threadFactory、handler之一为空,则报NullPointerException异常
 */
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    
    
}

Four, the constructor in detail

parameter Description
corePoolSize The number of core threads. When the number of threads is less than this value, the thread pool will give priority to creating new threads to perform new tasks
maximumPoolSize The maximum number of threads that the thread pool can maintain
keepAliveTime Lifetime of idle threads
unit The parameter keepAliveTime is the unit of the survival time of the idle thread. This is an enumerated class
workQueue Task queue, used to cache unexecuted tasks
threadFactory Thread factory. A more meaningful name can be set for the new thread through the factory
handler Rejection strategy. When the thread pool and task queue are both saturated, the rejection strategy is used to process new tasks. The default is AbortPolicy, that is, throw an exception directly

1. The corePoolSize
thread pool is empty by default, and the thread will only be created when the task is submitted. If the number of threads currently running is greater than corePoolSize, threads are created depending on the situation. If you call the prestartAllcoreThread method of the thread pool, the thread pool will create and start all core threads in advance to wait for tasks.

2. maximumPoolSize
If the task queue is full and the number of threads is less than the maximumPoolSize, the thread pool will still create new threads to process tasks

3. keepAliveTime
When the number of threads is greater than the core, this is the longest time that redundant idle threads wait for new tasks before terminating, and it will be recycled after this time.

If there are many tasks, and the execution time of each task is short, you can increase keepAliveTime to improve thread utilization. In addition, if the allowCoreThreadTimeOut property is set to true, keepAliveTime will also be applied to the core thread.

4. The time unit of the TimeUnit
keepAliveTime parameter. The optional units are Days, HOURS, MINUTES, SECONDS, MILLISECONDS, etc.

5. workQueue is
used to keep the queue of tasks before executing tasks. This queue will only save Runnable tasks submitted by the execute method. The task queue is of the BlockingQueue type, which is a blocking queue.

6. ThreadFactory
can use the thread factory to set a name for each created thread. Under normal circumstances, there is no need to set this parameter.

7. RejectedExecutionHandler
reject strategy. The handler to be used when the execution is blocked, because the thread limit and queue capacity are reached, note that it is not a common Handler, the default is AbordPolicy. Several of its strategies will be explained in detail in the next blog.

The construction parameters of ThreadPoolExecutor need to meet certain conditions:

  1. If one of the following situations occurs, an IllegalArgumentException will be thrown during the build:
    1. corePoolSize <0
    2. keepAliveTime <0
    3. maximumPoolSize <= 0
    4. maximumPoolSize <corePoolSize
  2. If one of the following situations occurs, a NullPointerException will be thrown during the construction process:
    1. workQueue is null
    2. threadFactory is null
    3. handler is null

Five, common ThreadPoolExecutor

Different types of ThreadPoolExecutor can be created by directly or indirectly configuring the parameters of ThreadPoolExecutor. Among them, 4 types of thread pools are commonly used: FixedThreadPool, CachedThreadPool, SingleThreadExecutor, ScheduledTheadPool.

1. FixedThreadPool


2. CachedThreadPool


3. SingleThreadExecutor


4. ScheduledTheadPool


to sum up

For advanced knowledge points such as thread creation strategy, thread resource recycling strategy, thread queuing strategy, thread rejection strategy, etc. in the thread pool , please read my other blog post on Android Thread Pool in a simple way (2)

Guess you like

Origin blog.csdn.net/luo_boke/article/details/107580536
Recommended