In Android development, thread pools under the java.util.concurrent package are often used for high-concurrency scenarios, which have the following advantages:

  1. Reusing threads in the thread pool to avoid performance overhead due to thread creation and destruction;
  2. Effectively control the maximum number of concurrent threads in the thread pool to avoid the blocking phenomenon caused by the mutual preemption of system resources between a large number of threads;
  3. Can manage threads, and provide periodic execution and periodic interval cycle execution and other functions.

The Executor interface under Java’s java.util.concurrent package is the top-level interface for task execution, and ThreadPoolExecutor is the true implementation class of the thread pool. ScheduledThreadPoolExecutor inherited ThreadPoolExecutor is the true implementation class of the thread pool, and on the basis of the ThreadPoolExecutor added support for periodic tasks. Concurrent package wraps the common calling methods into the Executors class, so we can usually invoke the methods in the Executors class to implement thread pool calls under normal scenarios.

A comparison of the four most common thread pools is as follows:

type Create method instructions
FixThreadPool Executors.newFiedThreadPool(int nThreads) A thread pool with a fixed number of threads, only core threads and no collection, no timeout mechanism
CachedThreadPool Executors.newCachedThreadPool() A thread pool with an indefinite number of threads. Only non-core threads are created to handle new tasks when all threads are active. Otherwise, idle threads are used, with a timeout of 60 seconds
ScheduledThreadPool Executors.newScheduledThreadPool(int corePoolSize) The number of core threads is fixed, and there is no limit on the number of non-core threads. Non-core threads are recycled immediately when they are idle, and are mainly used to perform scheduled tasks and repetitive tasks in a fixed period
SingleThreadExecutor Executors.newSingleThreadExecutor() There is only one core thread, ensuring that all tasks are executed sequentially in the same thread

The UML diagram for the related classes is shown below