Android_ Deep Analysis Asynctask

Source: Internet
Author: User

reprint: Special thanks to the Ronin starry sky, there are some modifications! http://blog.csdn.net/hitlion2008/article/details/7983449Inside the 1.AsyncTask

Asynctask has two main parts: one is the interaction with the main line, and the other is the management schedule of the thread. Although it is possible to have multiple instances of Asynctask subclasses, the internal handler and threadpoolexecutor of Asynctask are shared by the process, are static, or belong to the class, and the properties of the class are scoped to Classpath , because a process is a VM, it is asynctask that controls all instances of subclasses in the process scope.

2. Scheduling of thread tasks

Internally, a process-scoped thread pool is created to manage the tasks to run, which means that when you call Asynctask#execute (), Asynctask will hand over the task to the thread pool, which is managed by the thread pool to create the thread and run the Therad.

3. Different version differences
(1). API10 and Previous versions

The internal thread pool limit is 5, which means that only 5 threads can be run at the same time, and more than one thread can wait, waiting for the previous thread to execute before it is dispatched and run. In other words, if the number of Asynctask instances in a process is more than 5, then if the first 5 are running for a long time, then the 6th one can only wait for the opportunity. This is a limitation of asynctask and cannot be resolved for versions prior to 2.3. If your application requires a large number of background threads to perform tasks, then you can only abandon using asynctask, create a thread pool to manage thread, or simply use thread directly without the thread pool. Have to say, although asynctask is easier to use than thread, but it can only run up to 5 threads at the same time, which greatly limits its strength, you must carefully design your application, stagger the use of asynctask time, try to do ticks, or guarantee the number will not be more than 5 , or you may encounter the problem mentioned above. Otherwise, you can only use the API in Javase.

That is, the maximum can run at the same time as 5!

(2.API11 and later versions

Google is probably aware of the limitations of Asynctask and has made some tweaks to Asynctask's API starting with Android 3.0: The task submitted by #execute () has added two predefined thread pools Serial_executor ( The default is the sequence thread pool, which executes only one thread task at a time ) and Thread_pool_executor ( also the original default thread pool )

Run only one at a time in order, that is, it is in the order of submission, each time only one thread is started to perform a task, and then a second task is completed, which is equivalent to only one background thread executing the submitted task (Executors.newsinglethreadpool ())

Added interface #executeonexecutor () This interface allows developers to provide custom thread pool run and dispatch thread, if you want all tasks to run concurrently concurrently, create an unrestricted thread pool ( Executors.newcachedthreadpool ()) and provided to Asynctask. This asynctask instance has its own thread pool instead of using the Asynctask default.

In fact, Thread_pool_executor is not new, before it, just before (Android 2.3) It is asynctask private, not public. thread_pool_executor is a thread pool with a corepoolsize of 5, which means that at most 5 threads run at the same time, more than 5 will wait. So

If you use executeonexecutor (asynctask. Thread_pool_executor ) is the same as the 2.3 version of the Asynctask.execute () effect.

and Serial_executor is new, it is to ensure the order of the task execution, that is, it can ensure that the task is committed in order to do in sequence. It has a queue inside it to hold the submitted task, ensuring that only one is currently running, so that the task is executed in exactly the order that the default execute () uses, that is, Executeonexecutor (asynctask. Serial_executor) is the same as execute ().

4. Typical issues

Understanding Asynctask, if you find that the image asynchronous task has not yet been executed, it may be executed by the thread of Serial_executor order. Since there may be other places in the application that use Asynctask, the asynctask to take pictures from the network may wait until other tasks are complete, rather than calling executor () to execute immediately.

The workaround is simple, either by using thread directly or by creating a separate thread pool (Executors.newcachedthreadpool ()). Or the simplest solution is to use Executeonexecutor (asynctask.thread_pool_executor) so that at least you don't have to wait until the front ends.

5. Precautions and recommendations
    • Improve your design, less asynchronous processing

      Threads are very expensive, asynchronous processing is also error-prone, difficult to debug, difficult to maintain, so improve your design, as little as possible with async. For a generic database query, there is no need to start a thread for a small amount of I/O operations.

    • If there is no interaction with the main thread do not use asynctask

      Asynctask was designed to meet the specific needs of Android: non-Main thread cannot manipulate (UI) components, So the asynctask extension thread enhances the ability to interact with the main thread. If your app doesn't interact with the main thread, then it's OK to use thread directly.

    • When there is a need for a large number of threads to perform tasks, be sure to create a thread pool

      Threads are very expensive, especially if you create a new thread, or you do not have to design a tool such as a thread pool. When a large number of threads are required to perform a task, be sure to create a thread pool, whether it is using asynctask or thread, because the thread pool inside it is limited in number, may not meet the requirements, and thread pooling is used to manage the thread pool to avoid creating a large number of threads for the virtual machine. For example, from the network to download pictures in bulk, you do not want to one under, or 5 5 downloads, then create a corepoolsize 10 or 20 of the thread pool, each time 10 or 20 such a download, that is, to meet the speed, without wasting the useless performance overhead to create unlimited threads.

    • for asynchronous tasks that you want to start executing immediately, either by using thread directly or by creating a separate thread pool for Asynctask

      The default asynctask does not necessarily perform your task immediately unless you provide him with a separate pool of threads. If you do not interact with the main thread, you can create a thread directly, although the cost of creating threads is large, but if this is not a bulk operation there is no problem.

    • Android development is not as simple as it should be, spend more time and effort on code and testing to make sure the program is good

Use a custom corepoolsize of 7 executor (Executors.newfixedthreadpool (7)):

Use executor with no restrictions (Executors.newcachedthreadpool ()):

more 1
    • Previous Android_blockingqueue_ Concurrent Threads
    • Next article android_contentobserver and datasetobserver difference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.