Android multithreading and asynchronous Processing

Source: Internet
Author: User
1. Question 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
In an intuitive sense, 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-threaded implementation implements runnable or extends thread 3) multi-threaded core mechanism is handler 4) the following implementation methods are provided: ---- 1 ----- handler ------------ indicates that 1 must be associated with a logoff instance when creating a handler. The default constructor is handler (), which is associated with the Logoff of the current thread. Eg: we create a handler in the UI thread, and then we associate the Logoff of the UI thread! This can be seen from the source code! The simplified code is as follows: public handler () {mloler = Looper. mylooper (); // The Looper of the current thread. When the activity is created, the UI thread has created a looper object. // Looper is the core in the handler mechanism, it keeps reading messagequeue cyclically. If there is a message to be processed, it will send the message to the current handler instance to process if (mlooper = 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, mqueue = mloue. mqueue; // messagequeue of handler may fail. 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 loler. The Looper 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 can still perform business operations! Eg: -------------------- create a worker thread Private Static final class worker implements runnable
{
Private Static final object mlock = new object ();
Private loopdomainmlow.gov.cn;

Public worker (string name)
{
Final 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.
Looper. Prepare (); mloe = Looper. mylooper (); 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 loopereg: ---------------- of the worker to define our own handlerprivate 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 handlerthis. mworker = new worker ("workerthread") in the activity ");
This. mmyhandler = new myhandler (this. mworker. getlooper (); --------- create messagefinal message MSG = This. mmyhandler. obtainmessages (100); MSG. put ("test", "test"); MSG. sendtotarget (); note that each message must have its own target, that is, the handler instance! Source code: 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

; // 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? The following is a brief description: When the UI thread of the activity is created, it is associated with logoff and messagequeue. Then we create our own handler in the UI thread, handler belongs to the UI thread, so it can interact with the UI thread! The logoff of the UI thread is always executing the loop operation messagequeue to read the compliant message to its target
Handler to handle it! Therefore, we only need to put the latest data in the messagequeue Of The logoff associated with handler in the worker thread.
Logoff is always in the loop operation. Once there is a qualified message, the message will be handed over to the target of the message, that is, Handler.
Li! 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! To put it simply, the UI thread or worker thread provides messagequeue, And the handler fills in the message to it, The logoff reads the message from it, and then
It is handled by the target of the message, that is, Handler !! The handlmescript (Message
MSG) method called !! This is the core of multi-thread asynchronous processing in Android !! A little wordy !! **************************************** * ************************** Create handler in the UI thread [generally inherit handlemessage (Message msg )] | loop can belong to a UI thread or worker thread | from the messgequeueof Loopers, Loopers directly operate on loop((get, and execute msg.tar get in loop(get get. dispatchmessage (MSG); Call handlemessage (Message MSG) of handler | get message in worker thread, then pass in messagequeue ************************************* through handler *********************************** * ***************************** --------------- When creating a logoff, the messagequeue private loue (){
Mqueue = new messagequeue ();
Mrun = true;
Mthread = thread. currentthread ();
} ---- 2 ----- viewpost (runnable action) postdelay (runnable action, long miliseconds) ----- 3 ----- activityrunonuithread (runnable action) Implementation of this method is very simple: 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 ();
}
} Among them: muithread = thread. currentthread ();
Mhandler = new handler () ----- 4 ----- asynctask <Params, progress, result> Params, progress, and result are all data types, the type of the data to be processed by Params. The result returned after the result of the Progress type is processed by progress is a simple method of asynchronous processing! Method execution sequence: 1) onpreexecute () -- execute in the UI thread and perform some initialization operations. 2) doinbackground (Params... params) -- execute in the worker thread for time-consuming background processing. In this method, you can call publishprogress (Progress progress) for progress processing. 3) onprogressupdate (Progress progress) -- execute in Ui thread and process progress in real time 4) onpostexecute (result) -- execute in Ui thread, in doinbackground (Params... params) after return, call 5) oncancelled () -- execute in the UI thread and execute it after the asynctask instance calls the cancle (true) method. Pay attention to some cleaning operations: asynctask must be created in the UI thread. ex Ecute (Params... params); executed in the UI thread, and can only be executed once. To call execute (Params... params), you must recreate the asynctask object. The last three methods are implemented by handler! 3. One Note 1) You need to explore it for specific use! Just make bricks! 2) For some usage notes, see api reference! 2) it is best to trace and analyze the source code!

This article is from "Miao Yun Qi's blog
Blog, be sure to keep this source http://myqdroid.blog.51cto.com/2057579/392157

Related Article

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.