[turn] Jiangnan little Rain blog column -Android development thread pool use summary

Thread pools are one of the most common things in Android development, and wherever threads are involved, thread pools are involved in most cases. The use of thread pools in Android development is similar to the use of thread pools in Java. So today I want to summarize the use of thread pools in Android development.

OK, let’s say I want to make a news app, and there’s an item on the ListView, and each item has an image that needs to be loaded from the network. If you don’t use a thread pool, you might start a new thread as follows:

New Thread(new Runnable() {@override public void run() {// network access}}).start(); There are three main problems with this usage: ##1. Creating a new thread for each item leads to frequent threads being created, which are then reclaimed, which leads to frequent GC 2. This lack of unified management of multiple threads, the competition between threads, reduce the efficiency of the program, the mobile phone page stuck, and even lead to the program crash 3. If an item slides off the page, the loading of images on that item is stopped, but if threads are created this way, thread stop execution is not possible

These three problems can be solved by using thread pools.

##2. Benefits of using thread pools 1. Reuse good threads that have been created to avoid frequent GC 2. Control the number of concurrent threads, rationally use system resources, and improve application performance. 3. Effectively control the execution of threads, such as scheduled execution or cancellation

OK, we know that the thread pool in Android actually comes from Java. Java’s thread related thing is called Executor. Executor itself is an interface, and this interface has a very useful implementation class called ThreadPoolExecutor, as follows: