Relationships among multiple android Thread, Runnable, Handler, and AsyncTask

Source: Internet
Author: User

Android multithreading is actually java multithreading. The android UI thread is also called the main thread.

First, Thread and Runnable:

A Thread is a Thread, and Runnable can be understood as a task. This task is just an interface. The specific task is executed in the run () method.

Thread thread = new Thread (Runnable );

Put a Runnable task in the thread. When thread. start () is called, The system opens a new thread to execute. This runnable task is executed in multiple threads. It is executed in a new thread.

But thread. run (), this is actually only in the UI thread to execute Runnable and does not implement multithreading. There is no new thread in the system.

If new Runnable (). run (); is directly executed in the UI thread, no multi-thread operation is performed.

Conclusion: runnable () is just an abstract task, not a multi-thread. Thread. start (). Is a new multi-thread. And execute your run () method in the new Thread.


Let's take a look at Handler, the product of android's multi-thread communication mechanism.

The hanlder of the following three methods does not actually involve multithreading.

Post (Runnable) allows the current thread to execute the Runnable task. If it is called in the main thread, Runnable is executed in the UI thread. In fact, runnable is not executed in multiple threads.
PostAtTime (Runnable, long) also enables the current thread to execute Runnble long at the time point
PostDelayed (Runnable long) causes the current thread to delay long and then execute Runnable.

The three methods can actually regard handler as a task scheduler, rather than a multi-thread related.


SendEmptyMessage (int)
SendMessage (Message)
SendMessageAtTime (Message, long)
SendMessageDelayed (Message, long) method of sending a Message

HandleMessage (Message msg) is used for multi-thread communication of android hanlder.


We can see that the three threads share one Message Queue, one LoZ consumer? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys + 8 + ittPB0LXEz/vPoimhozwvcD4KPHA + we3N4jK49s/keys + keys/b7dtcjQxc + itcTP + 8 + keys + 8/large + PGJyPgo8L3A + large/large + zzLXEyv2 + large/Ww7vT0LG + large/large + zzLX308M8L3A + large + 1xM/fs8zKtc/ examples/examples + examples/examples + samples/samples + PGJyPgo8L3A + CjxwPr + samples/nT2s/fs8yz2LXEyrXP1qGjy/nS1M/samples + z9 + samples + zzLXEvK + samples/ ryKW/tL + 0ztLDx8/Rack + rack + CjwvcD4KPHA + yOe5 + rack/qs/6oaO/ydLUvqG/ycTctcTJ2b + rack PGJyPgo8L3A + Platform + platform/qs/6 w/fP1M/Platform + platform/fs8y68yi4 + b7d07K8/imjrM + Platform + platform/CvbWho8/fs8yz2L/Platform /fs8zK/cG/tvjIw8 + examples/examples + vSqs/examples + CjwvcD4KPHA + signature + TIu7K7zKu/samples + signature + CjwvcD4KPHA + signature + Signature =" brush: java; "> public static final Executor SERIAL_EXECUTOR = new SerialExecutor ();This is a static thread pool object. The thread pool shared by this process. (I don't know if all android programs share this thread pool .. Please show up .)

Public final AsyncTask
 
  
Execute (Params... params) {return executeOnExecutor (sDefaultExecutor, params);} public final AsyncTask
  
   
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) ") ;}} // Status indicates that the background thread is running mStatus = Status. RUNNING; // execute the initialization operation inherited by the user onPreExecute (); // put the RUNNING parameters in the task mWorker. mParams = params; // exec.exe cute (mFuture); return this ;}
  
 

In this way, the thread pool executes the task mWorker.

MWorker = new WorkerRunnable
 
  
() {Public Result call () throws Exception {mTaskInvoked. set (true); Process. setThreadPriority (Process. THREAD_PRIORITY_BACKGROUND); // noinspection unchecked // The thread pool runs this task. And postResult sends out the result return postResult (doInBackground (mParams ));}};
 

The doInBackground () method is executed for this task. This task is executed in a multi-threaded environment through the thread pool. That is to say, doInBackground () is also executed in multiple threads.

private Result postResult(Result result) {        @SuppressWarnings("unchecked")        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,                new AsyncTaskResult
 
  (this, result));        message.sendToTarget();        return result;    }
 

Pass the result through Hanlder + message.

Private static class InternalHandler extends Handler {@ SuppressWarnings ({"unchecked", "success"}) @ Override public void handleMessage (Message msg) {AsyncTaskResult result = (AsyncTaskResult) msg. obj; switch (msg. what) {case MESSAGE_POST_RESULT: // There is only one result. mTask. finish (result. mData [0]); // processing result break; case MESSAGE_POST_PROGRESS: result. mTask. onProgressUpdate (result. mData); // process the intermediate data break; }}} private void finish (Result result) {if (isCancelled () {onCancelled (result );} else {onPostExecute (result);} mStatus = Status. FINISHED ;}



This hanlder processes the received message.

You can see that finish () is called and onPostExecute is called in finish to allow the user to use the result.



In conclusion, the multi-Thread implementation in Java is Thread implementation, which has little to do with runnable.

In android, handler + message + thread is used to implement multi-thread data communication because of the need for multi-thread data exchange. As far as hanlder itself is concerned, it does not implement multithreading.

Because handler + message + thread is relatively load-intensive, android provides AsyncTask to implement multithreading and has the ability to synchronize multi-threaded data.

The essence of AsyncTask is the implementation of handler + message + thread (thread pool. Therefore, it is sufficient to use asyncTask in android to simply use multiple threads.



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.