SoFunction
Updated on 2025-04-05

Summary of the usage of four thread pools that come with Android

In Android development, if we want to execute a time-consuming task, we generally consider starting a thread to process it.

Because we all know that a thread run method is actually over after it is executed, but this is just the end and has not been recycled. It will be idle there, waiting for GC to recycle. So if we new a thread for every task we perform, then in some extreme scenarios, it consumes memory.

In the previous memory optimization article, I talked about the concept of pool in Android, that is, the reuse mechanism, so there is also a thread pool for threads.

This article will first briefly introduce the four thread pools that come with Android:

1 、newCachedThreadPool

This kind of thread pool is relatively flexible, which means that the number of threads in its pool is not fixed. It can theoretically be infinitely large, and tasks do not need to be queued. If there are free threads, it will be reused, and if there is no thread, it will be created.

ExecutorService cachedThreadPool = ();
    (new Runnable() {

      @Override
      public void run() {
        // TODO Auto-generated method stub

      }
    });

2、newFixedThreadPool

This is a fair and well-used person, and is also used in the Android SDK source code. The number of threads in its pool has a maximum value, which can be set by itself. If this maximum value exceeds, the task will be added to the task queue and wait.

ExecutorService fixedThreadPool = (5);
    (new Runnable() {

      @Override
      public void run() {
        // TODO Auto-generated method stub

      }
    });

3、 newSingleThreadExecutor

As literally, this is a singletonized thread pool, which only has one thread to execute tasks. The most common example is our UI thread. It is a typical single-threaded model.

ExecutorService singleThreadExecutor = ();
    (new Runnable() {

      @Override
      public void run() {
        // TODO Auto-generated method stub

      }
    });

4、newScheduledThreadPool

This is also a fixed-length thread pool, but can support periodic tasks.

The following example shows that after one second delay, it is executed every two seconds.

ScheduledExecutorService scheduledThreadPool = (5);
    (new Runnable() {

      @Override
      public void run() {

      }
    },1, 2, );

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.