1. Questions raised
1 Why do I need multiple threads?
2 How to achieve multithreading?
3 What is the core of multithreaded mechanism?
4 in the end how many ways to achieve?
2, problem analysis
1 Why the need for multithreading is the nature of asynchronous processing, intuitive point is not to let users feel "very card."
Eg: you click the button to download a song, and then the button is in the pressed state, then the user experience is very poor.
2 multithreading Implementation mode implements Runnable or extends thread
3 multithreading core mechanism is handler
4) provides the following implementation methods
--1-–handler
———————————— Note 1
When creating a handler, be sure to associate a Looper instance, the default constructor handler (), which is the looper associated with the current thread.
eg
We create a handler in UI thread, then the looper! of UI thread is associated at this point
This point from the source can be seen!
The simplified code is as follows:
Copy Code code as follows:
Public Handler () {
Mlooper = Looper.mylooper ();
The looper of the current thread, and the UI thread has created the Looper object when the activity is created
In the handler mechanism, Looper is the most core, it has been in the cycle of reading MessageQueue, there
The message to process is sent to the current handler instance to process
if (Mlooper = = null) {
throw New RuntimeException (
"Can ' t create handler inside thread that has not called looper.prepare ()");
}
As you can see from the above, a handler instance must be associated with a Looper object, otherwise an error
Mqueue = Mlooper.mqueue;
Handler's MessageQueue, is it FIFO? No! I feel like it should be in chronological order.
Of What is the relationship between message and MessageQueue? Interested can study the source code!
Mcallback = null;
}
When creating a handler, you can also specify Looper, at which point the Looper object can be either the current thread or another thread!
Handler only deals with the message in the MessageQueue of its associated looper, as to which thread looper,handler is not very concerned!
eg
We created the handler instance in the UI thread, which is then passed into the looper of the worker thread, where business operations can still take place!
eg
—————— – Create worker threads
Copy Code code as follows:
Private static Final class Worker implements Runnable
{
private static final Object Mlock = new Object ();
Private Looper Mlooper;
Public Worker (String name)
{
Final thread thread = new Thread (null,this,name);
Thread.setpriority (thread.min_priority);
Thread.Start ();
Synchronized (Mlock)
{
while (Mlooper = = null)
{
Try
{
Mlock.wait ();
}
catch (Interruptedexception e)
{
E.printstacktrace ();
}
}
}
}
@Override
public void Run () {
Synchronized (Mlock)
{
This method can only be executed once, and a thread can only associate one Looper
Looper.prepare ();
Mlooper = Looper.mylooper ();
Mlock.notifyall ();
}
Looper.loop ();
}
Public Looper Getlooper ()
{
return mlooper;
}
public void Quit ()
{
Mlooper.quit ();
}
}
We can create a handler in the UI thread and pass in the worker Looper
eg
—————-define your handler.
Copy Code code as follows:
Private Final class MyHandler extends Handler
{
Private long ID;
Public MyHandler (Looper looper)
{
Super (Looper);
}
@Override
public void Handlemessage (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 ();
It should be noted that each message must have its own target that handler instance!
The source code is as follows:
Copy Code code 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.target = h;//can see that the message is associated with the current handler
M.what = what;
return m;
}
The above is just a little bit of the original rational explanation!
We usually use handler is mainly used to handle the asynchronous interactive problem of multithreading!
Because Android requires only UI threads to update the user interface and accept user buttons and touch events!
Then you must ensure that the UI thread cannot be blocked, so time-consuming operations must open a new thread to handle!
So the question is, how can the latest data be fed back to the user after the time-consuming operation is over? And we are currently working in a worker thread, so that UI updates are not available.
So what do we do? You must pass the latest data to the UI thread where it can be handled! I'm sending it to handler now! But what the hell did handler do? The brief description is as follows:
When the UI thread in which the activity is created is associated with Looper and MessageQueue, then we create our own handler in the UI line Chengri, so handler is part of the UI thread, so it can interact with the UI thread!
The looper of the UI thread has been in the loop operation MessageQueue read the required message to the target that belongs to it handler to deal with! So, all we have to do is put the latest data into the MessageQueue of the looper associated with handler in the worker thread, but Looper has been operating in the loop, and once there is a message that meets the requirements, The first time the message to the target of the message handler to deal with! So, when we create the message, we should specify its target, 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, then handler automatically sets target for the message. Can look at the source!
The simple thing to say is:
The UI thread or worker thread provides messagequeue,handler to fill in the Message,looper from which to read the message, and then submit the message to its own target, handler, to process!! The HANDLMESSAG (Message msg) method, which is eventually handler from the UI thread, is called!!
This is the most important part of Android multithreading asynchronous processing!!
A little wordy Ah!!
*******************************************************************
Creating handler[in the UI thread General inheritance Handlemessage (Message msg)]
|
Looper can belong to a UI thread or a worker thread
|
The messgequeue,looper that belongs to Looper has been operating in loop (), executing msg.target.dispatchMessage (msg) in loop (), and calling Handler Handlemessage ( Message msg)
|
Gets the message in the worker thread and then passes the handler through the MessageQueue
*******************************************************************
————— – When you create a looper, you create a MessageQueue that belongs to the Looper
Private Looper () {
Mqueue = new MessageQueue ();
Mrun = true;
Mthread = Thread.CurrentThread ();
}
--2-–view
Post (Runnable action)
Postdelay (Runnable action, long miliseconds)
-–3-–activity
Runonuithread (Runnable action)
The implementation of this method is 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 ();
}
}
which
Muithread = Thread.CurrentThread ();
Mhandler = new Handler ()
-–4-–asynctask
Params,progress,result are all data types,
Params the type of data to be processed
Types of progress processing progress
Results returned after result processing
It is a simple method of asynchronous processing!
The order in which the methods are executed:
1)
OnPreExecute () – Executing in the UI thread, doing some initialization
2)
Doinbackground (Params ... Params) – executed in a worker thread, time-consuming background processing in which publishprogress (Progress Progress) can be invoked for progress processing
3)
Onprogressupdate (Progress Progress) – Executed in the UI thread, real-time processing of progress
4) OnPostExecute-execute in the UI thread, Doinbackground (Params ... Params) after return call
5)
Oncancelled () – Executes in the UI thread, executes after the Asynctask instance calls the Cancle (True) method, and performs some cleanup operations
A few notes:
Asynctask must be created in the UI thread.
Asynctask.execute (Params. Params); Executed in the UI thread and only once
To invoke execute again (Params ... Params), you must re-create the Asynctask object
The latter 3 kinds of methods are essentially using handler to achieve!