Summary of the use of four thread pools provided with Android

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

As we all know, a thread is really finished only after the run method is executed. However, it is only finished and has not been recycled. It will remain idle and wait for GC to recycle. Therefore, if we create a new thread for each task, it will consume memory in some extreme scenarios.

In the previous article on memory optimization, 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 first briefly introduces the four thread pools in Android:

1 、newCachedThreadPool

This thread pool is more flexible, that is, the number of threads in its pool is not fixed. In theory, it can be unlimited. Tasks do not need to queue. If there are idle threads, they will be reused, and if not, new threads will be created.

2、newFixedThreadPool

This is a regular one, and it is also widely used in the source code of Android SDK. The number of threads in its pool has a maximum value, which can be set by yourself. If the maximum value is exceeded, the task will join the task queue to wait.

3、 newSingleThreadExecutor

Literally, this is a singleton thread pool. It has only one thread to execute tasks. The most common example is our UI thread. It is a typical single thread model.

4、newScheduledThreadPool

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

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

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>