Android multithreading and asynchronous Processing

Source: Internet
Author: User

1. Question proposal
1) Why multithreading is required?
2) How to Implement multithreading?
3) What is the core of the multithreading mechanism?
4) How many implementation methods are there?

2. Problem Analysis
1) The essence of Multithreading is asynchronous processing. Simply put, users should not feel "very stuck ".
Eg: If you click the button to download a song and the button is pressed, the user experience will be poor.

2) multi-Thread implementation implements Runnable or extends Thread

3) the core mechanism of Multithreading is Handler.

4) provides the following implementation methods:
-- 1 -- Handler
------------ Description 1
When creating a Handler, you must associate it with a logoff instance. The default constructor is Handler (), which is the logoff associated with the current Thread.
Eg:
Create a Handler in the UI Thread, and then associate the Logoff of the UI Thread!
This can be seen from the source code!
The simplified code is as follows:Copy codeThe Code is as follows: public Handler (){
Mlogoff = logoff. mylogoff ();
// Logoff of the current thread. When the Activity is created, the UI thread has created a logoff object.
// In the Handler mechanism, logoff is the core, which is always in the loop read MessageQueue, which has
// The Message to be processed is sent to the current Handler instance for processing.

If (mloiter = null ){
Throw new RuntimeException (
"Can't create handler inside thread that has not called logoff. prepare ()");
}
// As shown in the preceding figure, a Handler instance must be associated with a logoff object; otherwise, an error occurs.

MQueue = mloue. mQueue;
// Handler's MessageQueue. Is it FIFO? No! I think it should be sorted by time.
! What is the relationship between Message and MessageQueue? If you are interested, you can study the source code!

MCallback = null;
}

When creating a Handler, you can also specify the logoff. At this time, the logoff object can be the current thread or other threads!
Handler only processes the Message in MessageQueue Of The logoff associated with it. As for the Logoff of the thread, Handler is not very concerned about it!
Eg:
We have created a Handler instance in the UI thread. At this time, it is passed to the Logoff of the Worker thread, and business operations can still be performed!
Eg:
------- Create a worker threadCopy codeThe Code is as follows: private static final class Worker implements Runnable
{
Private static final Object mLock = new Object ();
Private loopdomainmlow.gov.cn;

Public Worker (String name)
{
Final Thread thread = new Thread (null, this, name );
Thread. setPriority (Thread. MIN_PRIORITY );
Thread. start ();

Synchronized (mLock)
{
While (mloiter = null)
{
Try
{
MLock. wait ();
}
Catch (InterruptedException e)
{
E. printStackTrace ();
}
}
}
}

@ Override
Public void run (){
Synchronized (mLock)
{
// This method can be executed only once. One Thread can be associated with only one logoff.
Logoff. prepare ();
Mlogoff = logoff. mylogoff ();
MLock. policyall ();
}
Logoff. loop ();
}

Public Looper getLooper ()
{
Return mLooper;
}

Public void quit ()
{
Mloit. quit ();
}
}

We can create a Handler in the UI thread and import the Logoff of the Worker at the same time.
Eg:
------ Define your own HandlerCopy codeThe Code is as follows: private final class MyHandler extends Handler
{
Private long id;

Public MyHandler (low.logoff)
{
Super (logoff );
}

@ Override
Public void handleMessage (Message msg ){
Switch (msg. what)
{
Case 100:
MTv. setText ("" + id );
Break;
}
}
}

--- Create Handler in Activity
This. mWorker = new Worker ("workerThread ");
This. mMyHandler = new MyHandler (this. mWorker. getLooper ());

--- Create Message
Final Message msg = this. mMyHandler. obtainMessage (100 );
Msg. put ("test", "test ");
Msg. sendToTarget ();

Note that each Message must have its own Target, that is, the Handler instance!
The source code is as follows:Copy codeThe Code is as follows: public final Message obtainMessage (int what)
{
Return Message. obtain (this, what );
}

Public static Message obtain (Handler h, int what ){
Message m = obtain ();
M.tar get = h; // you can see that the message is associated with the current Handler.
M. what = what;
Return m;
}

The above is just a brief description of the principles!

Handler is usually used to handle Asynchronous interaction with multiple threads!
Android requires that only the UI thread can update the user interface and accept user buttons and touch events!
Therefore, you must ensure that the UI thread cannot be blocked, so that a new thread must be enabled for time-consuming operations!
The problem arises. After the time-consuming operation is over, how can we report the latest data to users? However, we currently work in the Worker thread, so we cannot update the UI.
So what should we do? You must pass the latest data to a place that can be processed by the UI thread! Now I am dispatched to Handler! What did Handler do? Brief description:
When the UI thread of the Activity is created, it is associated with logoff and MessageQueue. Then we have created our own Handler in the UI thread, so Handler belongs to the UI thread, thus, it can interact with the UI thread!
The logoff of the UI thread is always executing the Loop operation MessageQueue to read the conforming Message and send it to its target, that is, Handler! Therefore, we only need to put the latest data in the MessageQueue Of The logoff associated with Handler in the Worker thread. However, logoff is always in the loop operation. Once there is a Message that meets the requirements, the target of the Message is Handler! Therefore, when creating a Message, we should specify its target as Handler!
But we can also, new Message ()-> mHandler. sendMessage (msg); this is a special case!
If we get the Message object through the obtainMessage () method, Handler will automatically set the target of the Message. Check the source code!

Simply put:
The UI thread or Worker thread provides MessageQueue. Handler fills in the Message to it, and logoff reads the Message from it, and then submits it to the target of the Message, that is, Handler !! It is finally called from the handlmescript (Message msg) method of the Handler of the UI thread !!

This is the core of multi-thread asynchronous processing in Android !!
A little wordy !!

**************************************** ***************************
Create a Handler in the UI thread [generally inherit HandleMessage (Message msg)]

|
Logoff can belong to the UI thread or Worker thread

|
From the messgequeuethat belongs to Loopers, Loopers operate directly on loop(metadata, and execute msg.tar get. dispatchMessage (msg) in loop(metadata; call Handler's handleMessage (Message msg)

|
Get the Message in the Worker thread, and pass in MessageQueue through Handler
**************************************** ***************************

------ When creating a logoff, A MessageQueue belonging to the logoff is created.
Private logoff (){
MQueue = new MessageQueue ();
MRun = true;
MThread = Thread. currentThread ();
}

-- 2 -- View
Post (Runnable action)
PostDelay (Runnable action, long miliseconds)

-- 3 -- Activity
RunOnUiThread (Runnable action)
This method is easy to implement:
Public final void runOnUiThread (Runnable action ){
If (Thread. currentThread ()! = MUiThread ){
// If the current thread is not a UI thread
MHandler. post (action );
} Else {
Action. run ();
}
}
Where:
MUiThread = Thread. currentThread ();
MHandler = new Handler ()

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.