Android Learning Note: Concurrency issues for multiple asynctask instances

Source: Internet
Author: User

Asynctask is a simple, lightweight, multi-threaded class that Android provides to developers, and through it we can easily create a new thread Chengyang do time-consuming operations in the background (such as IO operations, network access, etc.) and update the UI during this process. It is lightweight because it does not need to use the knowledge of handler, thread and so on, it is relatively simple to use, but also loses some flexibility, it is inconvenient for some complicated scenes to be processed.

If you create and run only one Asynctask instance at a time in an app process, there is no problem. However, if there are multiple asynctask tasks executing simultaneously in a process, the problem is more complicated. Let's look at the example below (our example is running in Android 4).

First, test 1 (the default multiple tasks are serially executed)

1. Create a default app project

2, create a class to inherit Asynctask, the code is as follows

Package Com.example.asynctaskdemo;import Android.os.asynctask;public class Myasynctask extends Asynctask<string, Void, string>{private string name;public myasynctask (string name) {this.name = name;} @Overrideprotected string Doinbackground (String ... params) {System.out.println (name+ "is run" + System.currenttimemillis () + "thread id" +thread.currentthread (). GetId ()); try {thread.sleep (1000*10);} catch (Interruptedexception e) {e.printstacktrace ();} return null;}}

3. Use the task in the OnCreate method of the activity, as shown in the code below

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); for (int i=1;i<5;i++) {myasynctask task = new Myasynctask ("task" +i); Task.execute (New String [0]);}}

In the Debug window, we observe the interval and order of Myasynctask printing information. It is found that the 4 tasks created are serially executed and not concurrent.

The implementation details of Asynctask are studied, and when a asynctask is created and executed by its Execute method, Asynctask does not create a separate thread to execute. Asynctask is a thread pool that manages and dispatches all the tasks in a process.

in the Android2.3 Previous version (Sdk/api is greater than or equal to 10 version)

Multiple asynctask tasks are executed concurrently, meaning that if more than one task is started, it is executed concurrently. However, the number of concurrent executions depends on the number of thread pool limits within Asynctask. If this limit is exceeded, the new task can only wait.

on Android 3.0 and later (SDK/API is greater than or equal to 11 version)

Google began to make some changes to Asynctask's schedule execution from Android 3.0, running only one at a time in sequence for the tasks submitted by execute. This means that 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. This is verified in the example above.

Second, let asynctask concurrent execution

Because more than one task is serial by default, how do you let concurrency execute? Asynctask adds a new interface Executeonexecutor, which allows the developer to provide custom thread pool running and dispatching thread. Let's change the code above:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); for (int i=1;i<11;i++) {myasynctask task = new Myasynctask ("task" +i);//task.execute (new String[0]); Task.executeonexecutor (Asynctask.thread_pool_executor, New string[0]);}

Here we use the Executeonexecutor method instead of the Execute method. And the first parameter of the Executeonexecutor method is a predefined thread pool. These tasks can then be executed concurrently. At this point we observe the results of the printing, found that there are 5 tasks concurrent execution, you can see that there are 5 different thread numbers, view the source code of Asynctask, found that the number of concurrent threads is related to the number of CPU of the device, so the different devices may see the results are not exactly the same, this needs to be noted . Only after the previous 5 tasks have been executed, the subsequent ones are executed, and by the printed thread number you can see that the task behind is to reuse the original thread and not create a new thread, which is what the thread pool does.

Let's change the code and use another pre-defined thread pool provided by Android. The code is as follows:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); for (int i=1;i<11;i++) {myasynctask task = new Myasynctask ("task" +i);//task.execute (new String[0]); Task.executeonexecutor (Asynctask.serial_executor, New string[0]);}

Observing the print information we can see that, like the call to execute method, each task is executed serially. and up to 5 new threads were created in the process.

Iii. Custom Thread pool

We can use various static methods in Java.util.concurrent.Executors to create a thread pool for asynctask execution, and you can specify the number of threads and how to schedule them. There are many ways to do this, and we introduce two of them more commonly.

1. Let each Asynctask task execute on a single thread, that is, all is concurrent. Code such as:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Executorservice Newcachedthreadpool = Executors.newcachedthreadpool (); for (int i=1;i<11;i++) {MyAsyncTask task = new Myasynctask ("task" +i); Task.executeonexecutor (Newcachedthreadpool, New string[0]);}}

By observing printing, you can see that these tasks are performed concurrently.

2. Create a thread pool with the specified number of threads, and the maximum number of concurrent threads is the specified number. But new tasks are generated, and no idle threads are available to wait. Code such as:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Executorservice Newfixedthreadpool = Executors.newfixedthreadpool (3); for (int i=1;i<11;i++) {MyAsyncTask task = new Myasynctask ("task" +i); Task.executeonexecutor (Newfixedthreadpool, New string[0]);}}

As you can see from the observation, there are 3 threads executing concurrently.

In summary, as can be seen from the above example, if there are multiple tasks in a process that require concurrent execution, then you need to asynctask some deeper knowledge and have more questions to consider.

Android Learning Note: Concurrency issues for multiple asynctask instances

Related Article

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.