Android Thread (ii) asynctask (i)

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/itachi85/article/details/45041923

The basic usage of asynctask is not mentioned here, it is an Android developer.

1.android 3.0 ago Asynctask

private static final int core_pool_size = 5;  private static final int maximum_pool_size =;  Private static Final It keep_alive = ten;  ... private static final Threadpoolexecutor Sexecutor = new Threadpoolexecutor (core_pool_size,          maximum_pool_size, KEEP _alive, Timeunit.seconds, Sworkqueue, sthreadfactory);  

here we see the threadpoolexecutor, the principle of which I have already introduced in the previous article http://blog.csdn.net/itachi85/article/details/44874511 .

Here the number of threads that can run at the same time is 5, the total size of the thread pool is 128, and when the number of threads is greater than the core, the maximum time to wait for a new task is 10 seconds for the extra idle thread before terminating. Before 3.0, the Asynctask can have 5 tasks at the same time, while the asynctask can only have one task executing at the same time after 3.0.

2. Let's take a look at the Android 4.3 version of Asynctask

Asynctask constructor:

 /** * Creates a new asynchronous task.     This constructor must is invoked on the UI thread. */Public Asynctask () {mworker = new workerrunnable<params, result> () {public Result call () t                Hrows Exception {Mtaskinvoked.set (true);                Process.setthreadpriority (Process.thread_priority_background);            Noinspection unchecked return Postresult (Doinbackground (mparams));        }        }; Mfuture = new Futuretask<result> (mworker) {@Override protected void done () {T                ry {postresultifnotinvoked (get ());                } catch (Interruptedexception e) {ANDROID.UTIL.LOG.W (Log_tag, E); } catch (Executionexception e) {throw new RuntimeException ("An error occured while executing doinbackg                Round () ", E.getcause ()); } catch (Cancellationexception e) {postresultifnotinvoked (NULL);    }            }        }; }

This code initializes two variables, Mworker and mfuture, and passes the Mworker as a parameter when initializing the Mfuture. Mworker is a callable object, Mfuture is a Futuretask object that is temporarily stored in memory and used later.

When we use Asynctask, most of the time we call the Execute () method and look at the source code of execute ():

    Public final Asynctask<params, Progress, result> execute (params ... params) {        return Executeonexecutor ( Sdefaultexecutor, params);}

Returned the executeonexecutor and passed in Sdefaultexecutor (the default thread pool). First look at the source code of Executeonexecutor:

Public final Asynctask<params, Progress, result> executeonexecutor (Executor exec,            params ... params) {        if (Mstatus! = status.pending)  {            switch (mstatus) {case                RUNNING:                    throw new IllegalStateException ("Cannot execute task:"                            + "the task is Already running. ");                Case finished:                    throw new IllegalStateException ("Cannot execute task:"                            + "The task has already been executed" 
   
    + "(a task can be executed only once)");            }        }        Mstatus = status.running;        OnPreExecute ();        Mworker.mparams = params;        Exec.execute (mfuture);        return this;    }
   

The incoming thread pool exec invokes the Execute method and passes the mfuture mentioned above.

This incoming thread pool sdefaultexecutor is the default thread pool Serialexecutor, which is called the Execute () method of Serialexecutor:

  public static final Executor serial_executor = new Serialexecutor ();  private static volatile Executor sdefaultexecutor = Serial_executor;

Source code for Serialexecutor:

        private static class Serialexecutor implements Executor {        final arraydeque<runnable> mtasks = new Arraydeque< ; Runnable> ();        Runnable mactive;        Public synchronized void Execute (final Runnable R) {            Mtasks.offer (new Runnable () {public                void run () {                    try {
   r.run ();                    } finally {                        schedulenext ();}}            );            if (mactive = = null) {                schedulenext ();            }        }        protected synchronized void Schedulenext () {            if ((mactive = Mtasks.poll ())! = null) {                Thread_pool_ Executor.execute (mactive);}}}    


Call Serialexecutor's Execute method here you can see a runnable, this runnable is the Mfuture (Futuretask) mentioned above, the Nineth line executes the Futuretask Run method:

 public void Run () {if ' state! = NEW | | !            Unsafe.compareandswapobject (this, runneroffset, NULL, Thread.CurrentThread ()))        Return            try {callable<v> c = callable;                if (c! = null && state = = NEW) {V result;                Boolean ran;                    try {result = C.call ();                ran = true;                    } catch (Throwable ex) {result = null;                    ran = false;                SetException (ex);            } if (ran) set (result); }} finally {//runner must be non-null until state is settled to//prevent concurrent call            s to run () runner = null;            State must is re-read after nulling runner to prevent//leaked interrupts int s = State;   if (s >= interrupting)             Handlepossiblecancellationinterrupt (s); }    }


The C.call is executed in the Run method, where C is the Mworker (workerrunnable) we mentioned above. To execute the call method for workerrunnable:

Mworker = new Workerrunnable<params, result> () {public            Result call () throws Exception {                Mtaskinvoked.set ( true);                Process.setthreadpriority (process.thread_priority_background);                Noinspection unchecked                return Postresult (Doinbackground (Mparams));            }


Last line Postresult () method source code:

Private result Postresult (result result) {        @SuppressWarnings ("unchecked")        message message = Shandler.obtainmessage (Message_post_result,                new asynctaskresult<result> (this, RESULT));        Message.sendtotarget ();        return result;    }

We find that a message was sent that the above code sends a message that is accepted here:

private static class Internalhandler extends Handler {        @SuppressWarnings ({"Unchecked", "Rawuseofparameterizedtype "})        @Override public        void Handlemessage (Message msg) {            Asynctaskresult result = (Asynctaskresult) msg.obj;            switch (msg.what) {case                Message_post_result:                    //There are only one RESULT                    result.mTask.finish ( Result.mdata[0]);                    break;                Case message_post_progress:                    result.mTask.onProgressUpdate (result.mdata);                    Break;}}}    


The message is Message_post_result so will execute Result.mTask.finish (Result.mdata[0]), Finish Source:

  private void finish (result result) {        if (iscancelled ()) {            oncancelled (result);        } else {            OnPostExecute ( result);        }        Mstatus = status.finished;    }

Oncancelled (Result) is executed when canceled, otherwise it will be called onpostexecute (result), so we can get the result we need in the OnPostExecute to proceed to the next step.






Android Thread (ii) asynctask (i)

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.