In-depth analysis of AsyncTask concurrent execution

Source: Internet
Author: User

In-depth analysis of AsyncTask concurrent execution
1. it indicates that a strange phenomenon was found when AsyncTask was used, that is, when multiple tasks were created, they were executed one by one in order. After checking the information, we found that when we first introduced the task in 1.5, asyncTask execution (AsyncTask.exe cute () is sequential. When multiple AsyncTask tasks are executed simultaneously, they are executed one by one. The previous execution is complete before the execution is complete. In this way, executing multiple time-consuming tasks at the same time may not be the expected result, as in the case that the execute task will not be executed immediately, the task can be executed only after the previous task is executed.

In android 1.6 (Donut) to 2.3.2 (Gingerbread), the execution sequence of AsyncTask is modified to parallel execution. If multiple tasks are executed at the same time, these tasks are executed in parallel. When a task accesses the same resource, concurrency issues may occur.
In Versions later than Android 3.0 (Honeycomb), AsyncTask is modified to sequential execution and a new function executeOnExecutor (Executor) is added. If you need to execute in parallel, you only need to call this function and set the parameter to parallel execution. Create a separate thread pool (Executors. newCachedThreadPool ()). Or the simplest method is to use executeOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR). In this way, you do not have to wait until the previous steps are completed. ExecuteOnExecutor (AsyncTask. SERIAL_EXECUTOR) is the same as execute.
2. Source Code Analysis 1. The simplest case: sequential execution (AsyncTask. SERIAL_EXECUTOR). We first demonstrate the sequential execution. The Demo code is as follows:

@Overridepublic void onClick(View v) {try {for (int i = 0; i < 23; i++) {  new MultiThread(i).execute();  //new MultiThread(i).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);  //new MultiThread(i).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);}} catch (Exception e) {e.printStackTrace();}}class MultiThread extends AsyncTask
 
   {private int id;public MultiThread(int id){this.id=id;}@Overrideprotected void onPostExecute(Void result) {Log.i("AsyncTask", Thread.currentThread().getName()+id+"/"+new Date().getSeconds());}@Overrideprotected Void doInBackground(Void... params) {android.os.SystemClock.sleep(1000);return null;}}}
 
From the results, we can see that AsyncTask is executed sequentially and one is executed every second. From logcat, we can see that:
09-29 17:49:59.127: I/AsyncTask(18361): main0/5909-29 17:50:00.133: I/AsyncTask(18361): main1/009-29 17:50:01.144: I/AsyncTask(18361): main2/109-29 17:50:02.145: I/AsyncTask(18361): main3/209-29 17:50:03.147: I/AsyncTask(18361): main4/309-29 17:50:04.147: I/AsyncTask(18361): main5/409-29 17:50:05.148: I/AsyncTask(18361): main6/509-29 17:50:06.148: I/AsyncTask(18361): main7/609-29 17:50:07.149: I/AsyncTask(18361): main8/709-29 17:50:08.150: I/AsyncTask(18361): main9/809-29 17:50:09.150: I/AsyncTask(18361): main10/909-29 17:50:10.151: I/AsyncTask(18361): main11/1009-29 17:50:11.152: I/AsyncTask(18361): main12/1109-29 17:50:12.153: I/AsyncTask(18361): main13/1209-29 17:50:13.153: I/AsyncTask(18361): main14/1309-29 17:50:14.154: I/AsyncTask(18361): main15/1409-29 17:50:15.155: I/AsyncTask(18361): main16/1509-29 17:50:16.156: I/AsyncTask(18361): main17/1609-29 17:50:17.156: I/AsyncTask(18361): main18/1709-29 17:50:18.157: I/AsyncTask(18361): main19/1809-29 17:50:19.157: I/AsyncTask(18361): main20/1909-29 17:50:20.158: I/AsyncTask(18361): main21/2009-29 17:50:21.158: I/AsyncTask(18361): main22/21
2. Concurrent execution (AsyncTask. THREAD_POOL_EXECUTOR) First, let's look at the source code android. OS. AsyncTask , There are several key parameters we need to figure out.
    private static final String LOG_TAG = "AsyncTask";    private static final int CORE_POOL_SIZE = 5;    private static final int MAXIMUM_POOL_SIZE = 128;    private static final int KEEP_ALIVE = 1;    private static final ThreadFactory sThreadFactory = new ThreadFactory() {        private final AtomicInteger mCount = new AtomicInteger(1);        public Thread newThread(Runnable r) {            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());        }    };    private static final BlockingQueue
  
    sPoolWorkQueue =            new LinkedBlockingQueue
   
    (10);    /**     * An {@link Executor} that can be used to execute tasks in parallel.     */    public static final Executor THREAD_POOL_EXECUTOR            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
   
  
A. corePoolSize: Minimum number of threads maintained by the thread pool
B. maximumPoolSize: Maximum number of threads maintained by the thread pool
C. keepAliveTime: the idle time allowed by the thread pool to maintain the thread
D. unit: the unit of idle time allowed by the thread pool to maintain the thread.
E. workQueue: Buffer Queue used by the thread pool
F. handler: processing policy of the thread pool to reject tasks
When a task is added to the thread pool using the asynct.exe cuteOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR, 0) method:
If the number in the thread pool is smaller than corePoolSize, the thread remains active.
If the number in the thread pool is equal to corePoolSize, but the Buffer Queue workQueue is not full, the task is put into the Buffer Queue (the size is 10 ).
If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is smaller than maximumPoolSize, a new thread is created to process the added task.
@Overridepublic void onClick(View v) {try {for (int i = 0; i < 23; i++) { // new MultiThread(i).execute();  //new MultiThread(i).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);  new MultiThread(i).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);}} catch (Exception e) {e.printStackTrace();}}
The verification result is as follows:

If the number in the thread pool is greater than cZ limit? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys + qOssqLH0s/fs8yz2NbQtcTK/cG/keys + 8ztvNO1xMjOzvG5/keys + zzMr9us3S7LOjtKbA7UhhbmRsZXLAtL72tqi1xKGjPGJyPgo8cHJlIGNsYXNzPQ = "brush: java; "> try {for (int I = 0; I <250; I ++) {// new multithread(icmd.exe cute (); // new multithread(icmd.exe cuteOnExecutor (AsyncTask. SERIAL_EXECUTOR); new multithread(i0000.exe cuteOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR);} catch (Exception e) {e. printStackTrace ();}The execution result is as follows:

That's easy !!

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.