Android use the thread pool

A thread pool thread, why use the thread pool

1, Android in the thread

A distinction the main thread and the child thread in Android. The main thread is also known as the UI thread, mainly to deal with some things and interface-related, while the child thread is mainly used to deal with some of the larger time-consuming tasks, such as some network operations, IO requests, etc. If you handle these time-consuming tasks in the main thread, then there may be a phenomenon ANR (App directly stuck).

2, Android threads in the pool

Thread pool, from the show we know the meaning of the name of the thread pool thread that contains a pond, which play a role in the new thread, thread management, thread scheduling and so on.

3. Why should I use a thread pool

Now that Android already has the concept of threads, so why need to use the thread pool it? We give the reason for using a thread pool from two aspects.

  • First of all threads are consumed on New and destruction of property exist, if a period of time a large number of network requests, you will need to create and destroy multiple threads, loss in performance can be imagined.
  • Secondly, there are multiple threads of execution period will take up the CPU. We know that if there is only one CPU, the CPU executing threads are executed in turn will allocate time to each thread. If more than one child at the same time there is a thread, then the corresponding CPU execution time allocated to the main thread has become less, so App will very likely appear Caton phenomenon. In view of the above two reasons, we bring in the concept of such a thread pool, thread creation, scheduling, etc. are managed by the destruction of the thread pool, so you can reuse the threads do, do not always create a new thread, reduce thread creation and destruction of property loss. At the same time the thread pool will limit the number of threads created, so that the number of threads App is kept at a manageable range, so you can control multiple threads to seize the resources of the main thread.

Two, Android in the introduction of the thread pool

1, the thread pool construction

In Android thread pool is ThreadPoolExecutor object. We first look at the constructor of ThreadPoolExecutor.

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
复制代码

We were said about the current meaning of the several parameters: The first parameter is corePoolSize core number of threads , that is to say there are so many threads in the pool at least, even if there is no thread to perform the task. But there is one exception to this is if the thread pool allowCoreThreadTimeOut set to true, then the timeout (keepAliveTime) kernel thread will be destroyed after arrival. The second parameter is maximumPoolSize maximum number of threads in the thread pool . When the number of active threads reach this number, the new task will be added later blocked. The third parameter is keepAliveTime thread keep-alive time , that is, if there are more threads than the core thread pool thread count, then start the timer at the moment is not the task of the thread, if more than keepAliveTime, no new tasks come , the thread will be destroyed. And if the set allowCoreThreadTimeOut is true, the time is above the said first timeout . The fourth parameter unit to the third unit of the timing parameters , there milliseconds, seconds, and so on. The fifth parameter workQueue to the task queue thread pool , the queue holds Runnable object (the object is a Runnable task) passed over by the execute method. This type of task queue is BlockQueue type, that is blocking queue, when the number of the task queue is 0, the operation to take the task will be blocked; when the number of the task queue is full (active threads reached the maximum number of threads), add operation it will be blocked. The sixth parameter threadFactory is a thread factoryWhen you need to create a new thread pool thread, a thread factory use to provide a thread to the thread pool. The seventh parameter handler to reject the policy , when the thread pool using bounded queue (that is, the fifth parameter), if the queue is full, the task is added to the thread pool when a rejection policy.

2, classification of the thread pool

I、FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
复制代码

We can see FixedThreadPool building called ThreadPoolExecutor constructor. From the above it can be seen calling several features FixedThreadPool of:

  • It's the core number of threads and the maximum number of threads is the same, which means that when the thread is idle threads are not destroyed (because the number of maximum number of threads and core threads as). But the thread keep-alive time keepAliveTime set to 0, which means that when a thread pool thread when set to true allowCoreThreadTimeOut, in an idle state will soon be destroyed. When all threads are active, the new task will be in a wait state, and performed when there is idle threads.

II、CacheThreadPool

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
复制代码

You can see the call to build CacheThreadPool ThreadPoolExecutor constructor. From the above it can be seen calling several features CacheThreadPool of:

  • Its core thread count is 0, the maximum number of threads to Integer.MAX_VALUE (can be seen as a limitation). KeepAliveTime thread keep-alive time is 60 seconds. This means that when all threads in the pool are active, creates a new thread to perform the task; when there is idle thread pool thread (although there is no core thread, but the thread has 60 seconds to keep alive, and not idle down immediately be destroyed) on the use of idle threads. It should be noted that the task queue SynchronousQueue synchronous blocking queue, that queue does not have any capacity, only when there is a thread can perform tasks can add tasks to it. As can be seen from the characteristics of the above CacheThreadPool to ensure that there is a thread can perform tasks at any time (or to a new, or is idle threads), so there does not appear obstruction. About specific description BlockQueue, we can look at Java multithreading - Tools articles -BlockQueue this article. So for properties CacheThreadPool when we need to perform a number of tasks, but these tasks are time-consuming and relatively low, consider using CacheThreadPool.

III、ScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}	

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}
复制代码

You can see the call to build ScheduledThreadPoolExecutor ThreadPoolExecutor constructor. From the above it can be seen calling several features ScheduledThreadPoolExecutor of:

  • Its core number of threads is fixed, while the maximum number of threads to Integer.MAX_VALUE (can be seen as a limitation). KeepAliveTime thread keep-alive time is zero. This means that when the number of threads in the thread pool exceeds the core thread idle down will soon be destroyed. ScheduledThreadPool generally used to perform some task or a timing task is repeated some fixed period. May be performed by different delay executor.schedule (there are several different overloaded methods) respectively, the timing cycle repetitive tasks.

IV、SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
复制代码

You can see the call to build SingleThreadExecutor ThreadPoolExecutor constructor. From the above it can be seen calling several features SingleThreadExecutor of:

  • Its core number of threads is 1, 1 is the maximum number of threads, the thread keep-alive time keepAliveTime is 0, which means that at most only allow a thread pool thread exists and whether the thread is running or idle, are not It is destroyed. SingleThreadExecutor to ensure that all tasks are executed in the order in a thread.

Guess you like

Origin juejin.im/post/5d7318915188256f3b09bb50