Android threading and thread pool-----asynctask (i) "Android Development Art and exploration"

Source: Internet
Author: User

Threading is an important concept in Android, where threads are divided into the main thread and sub-threads, the main course is responsible for page correlation, and the child threads are responsible for time-consuming operations.

In addition to the thread itself in Android there is Asynctask Intentservice handlerthread.

Asynctask
     Public Abstract class Asynctask<params, Progress, result>  

1 Params parameter type
2 Progress Execution Progress type
3 Result return Data type

No parameters can be substituted with void

It provides 4 core methods:
    //called before an asynchronous task executes, typically to perform some preparation operations@Overrideprotected voidOnPreExecute () {Super. OnPreExecute (); }             //An online pool call for performing asynchronous tasks@Overrideprotectedstring Doinbackground (String ... params) {return NULL; }             //when an asynchronous task executes, it calls the@Overrideprotected voidOnPostExecute (String result) {Super. OnPostExecute (Result); }             //The main thread executes, the background task execution progress changes the call@Overrideprotected voidonprogressupdate (Void ... values) {Super. Onprogressupdate (values); }  

Note: The 1 Asynctask class must be loaded in the main thread 2 Asynctask objects must be created in the main thread 3 execute must be called on the UI thread for 41 Asynctask objects can only be executed once, that is, only once the Execute method is invoked
Working principle:
     Public FinalAsynctask<params, Progress, result>Execute (params ... params) {returnExecuteonexecutor (sdefaultexecutor, params); The Execute method calls the Executeonexecutor method; Take a look at the Executeonexecutor method: Public FinalAsynctask<params, Progress, result>Executeonexecutor (Executor exec, params ... params) {if(Mstatus! =status.pending) {Switch(mstatus) { CaseRUNNING:Throw NewIllegalStateException ("Cannot execute task:" + "The task is already running."));  CaseFinished:Throw NewIllegalStateException ("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; }  

You can see that a thread pool is encapsulated, and then I find out.

    Private Static volatileExecutor Sdefaultexecutor =Serial_executor;  Public Static FinalExecutor Serial_executor =NewSerialexecutor (); Private Static classSerialexecutorImplementsExecutor {FinalArraydeque<runnable> Mtasks =NewArraydeque<runnable>();                    Runnable mactive;  Public synchronized voidExecuteFinalRunnable R) {Mtasks.offer (NewRunnable () { Public voidrun () {Try{r.run (); } finally{schedulenext ();                  }                      }                  }); if(Mactive = =NULL) {schedulenext (); }              }  

From Serialexecutor, Asynctask is the process of queuing execution.

The system first encapsulates the Asynctask parameter params as a Futuretask object, and then futuretask to the Serialexecutor execute handler,
The Execute method gives the Futuretask to the Mtasks task queue, and if there is no asynctask task at this point, Serialexecutor Schedulenext () to perform the next task. When a task is finished, Serialexecutor will perform other tasks, and you can see that the Asynctask is serial.


The Asynctask constructor has a code like this:

    New Workerrunnable<params, result>() {                  publicthrows  Exception {                      Mtaskinvoked.set (true);                            Process.setthreadpriority (process.thread_priority_background);                       // noinspection unchecked                      return Postresult (Doinbackground (Mparams));                  }              ;  

Then look at the Futuretask Run method:

derive to my code slice Public voidrun () {if(state! = NEW | | !unsafe.compareandswapobject ( This, Runneroffset,NULL, Thread.CurrentThread ())) return; Try{callable<V> C =callable; if(c! =NULL&& state = =NEW)                      {V result; Booleanran; 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 was settled to//prevent concurrent calls to run ()Runner =NULL; //State must is re-read after nulling runner to prevent//leaked interrupts                ints =State ; if(S >=interrupting) Handlepossiblecancellationinterrupt (s); }          }  

The Futuretask Run method was found to perform the call of Mworker, so call is also executed in the thread pool.


Mworker call will Mtaskinvoked.set (true), indicating that the current task has been called and executed Asynctask's Doinbackground method and then
The return value is passed to the Postresult method;

    Private result Postresult (result result) {            @SuppressWarnings ("Unchecked")            = gethandler (). Obtainmessage (Message_post_result,                    new asynctaskresult<result> (this, result));            Message.sendtotarget ();             return result;        }  

You can see that Postresult sends a MESSAGE_POST_RESULT message through a handler

    Private StaticHandler gethandler () {synchronized(Asynctask.class) {                  if(Shandler = =NULL) {Shandler=NewInternalhandler (); }                  returnShandler; }          }                      Private Static classInternalhandlerextendsHandler { PublicInternalhandler () {Super(Looper.getmainlooper ()); } @SuppressWarnings ({"Unchecked", "Rawuseofparameterizedtype"}) @Override Public voidhandlemessage (Message msg) {Asynctaskresult<?> result = (asynctaskresult<?>) Msg.obj; Switch(msg.what) { CaseMessage_post_result://there is only one resultResult.mTask.finish (result.mdata[0]);  Break;  CaseMESSAGE_POST_PROGRESS:result.mTask.onProgressUpdate (Result.mdata);  Break; }              }          }  

When the handler receives the Message_post_result message, the finish method is called.

    Private void Finish (Result result) {              if  (iscancelled ()) {                  oncancelled (result);               Else {                  OnPostExecute (result);              }               = status.finished;          }  

If cancel execution is oncancelled, otherwise call OnPostExecute this method.

Android threading and thread pool-----asynctask (i) "Android Development Art and exploration"

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.