Runnable does not necessarily open a new thread, such as the following method of invocation is run in the main thread of the UI:
Handler mhandler=new Handler (); Mhandler.post (New Runnable () {@Override public void run () {//TODO auto-generated method stub} });
The official explanation for this method is as follows: "The runnable would be run on the user interface thread. ”
Boolean android.view.View. Post (Runnable action)
Causes the Runnable to is added to the message queue. The runnable'll be run on the user interface thread.
Parameters:
Action the Runnable that would be executed.
Returns:
Returns true if the Runnable is successfully placed in to the message queue. Returns false on failure, usually because the Looper processing the message queue is exiting.
We can pass the Runnable object (usually the subclass of runnable) by calling Handler's post method, and handler will invoke the Looper run method in runnable.
Runnable is an interface, not a thread, and a generic thread implements Runnable. So if we use an anonymous inner class that is running on the main thread of the UI, if we use the threading class that implements the Runnable interface, it is run on the corresponding thread.
Specifically, this function works as follows:
View.post (Runnable) method. In the post (Runnable action) method, view obtains the handler of the current thread (that is, the UI thread) and then posts the action object into the handler. In handler, it wraps the action object passed in as a message (the callback of the message is the action) and then puts it into the message loop of the UI thread. When handler processes the message again, there is a branch (the one that is not explained) that is set for it to call the runnable run method directly. At this point, it has been routed to the UI thread, so we can update the UI with no worries.
As seen earlier in the code, we here message callback for an anonymous inner class of runnable
In this case, do not make complex computational logic because it is not used in a new thread.
Why Android doesn't allow a new thread to update the UI, but instead uses handler to update the interface
Operations are likely to be concurrent, and the interface has only one
It's one thing to queue up for tickets.
There are too many people to buy tickets, only one to sell tickets.
If you open multiple threads and ask 100 people to buy tickets at the same time without standing in line, what will happen-
Similarly, you open multi-threading, let 100 threads to set the same TextView display content, each display content is different, it should listen to who?
So why not just new one and use a so-called handler?
Just because new has a strand friend to use handler,
What do I handler to update the UI in the main thread? Superfluous
Like only 1 people to buy tickets, sell tickets will tell him: comrade, please line up!?
The handle is the main thread, and threads are from the threading. Control data changes only in the main thread, so use handle
Update UI can only be done on the mainline thread, otherwise it will be an error. But sometimes we need to update ui,handler on the thread of the sub-line, it can pass the thread's data to the main threads, and let the primary thread synchronize operation to update the UI.
Let's take a look at this example
Package Com.hua;
Import android.app.Activity;
Import Android.os.Bundle;
public class Updateuinum1activity extends Activity {
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
New Thread (new Runnable () {
@Override
public void Run () {
Settitle ("Fengyi.hua");
}
});
}
}
The above is to implement a thread to update the title, you can implement this function, refresh the UI interface. This is wrong, however, because it violates the single-threaded model: Android UI operations are not thread-safe and must be executed in the UI thread.
Some people think this method is really redundant, why, because since it is refreshed once, I can completely in the main thread to perform the operation of refreshing the title, why also open the thread. This is because it may involve delays or other. For example, wait for 1min before the refresh operation, this time period to ensure that the main UI thread is operable, so use the thread to update. But this does conflict with Android's single-threaded model and is not recommended. Examples of using errors are as follows:
Package Com.hua;
Import Java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
public class Updatetitleactivity extends Activity {
private void Updatetitle () {
Date date = new Date ();
int hour, minute, second;
String Shour, Sminute, Ssecond;
Hour = (date.gethours () + 8)% 24;
minute = Date.getminutes ();
Second = Date.getseconds ();
if (Hour < 10) {
Shour = "0" + hour;
} else {
Shour = "" + hour;
}
if (minute < 10) {
Sminute = "0" + minute;
} else {
Sminute = "" + Minute;
}
if (second < 10) {
Ssecond = "0" + second;
} else {
Ssecond = "" + second;
}
Settitle ("Current time:" + Shour + ":" + Sminute + ":" + Ssecond);
}
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Timer timer = new timer ();
Timer.scheduleatfixedrate (New MyTask (), 1, 1000);//Here is the use of a timer, with the use of thread is an effect. Performance
The effect is to update the title multiple times to see if there is a problem.
}
Private class MyTask extends TimerTask {
@Override
public void Run () {
Updatetitle ();
}
}
}
The above code is used to refresh the title every 1s to show the current time. However, because Android is a single threaded model, there is a thread safety problem, so when the second refresh, there is an error.
The right approach
The two methods described above are the thread method, and the TimerTask method, respectively. is commonly used in Java because of thread safety. But in the single-threaded model of Android, it is not available. There are 2 correct methods.
1.thread+handler
2.timertask+handler
3.runnable+handler.postdelayed (Runnable,time)
Example: Timertask+handler
Package Com.hua;
Import Java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
public class Updatetitleactivity extends Activity {
Private Handler Mhandler = new Handler () {
@Override
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
Switch (msg.what) {
Case 1:
Updatetitle ();
Break
Default
Break
}
}
};
private void Updatetitle () {
Date date = new Date ();
int hour, minute, second;
String Shour, Sminute, Ssecond;
Hour = (date.gethours () + 8)% 24;
minute = Date.getminutes ();
Second = Date.getseconds ();
if (Hour < 10) {
Shour = "0" + hour;
} else {
Shour = "" + hour;
}
if (minute < 10) {
Sminute = "0" + minute;
} else {
Sminute = "" + Minute;
}
if (second < 10) {
Ssecond = "0" + second;
} else {
Ssecond = "" + second;
}
Settitle ("Current time:" + Shour + ":" + Sminute + ":" + Ssecond);
}
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Timer timer = new timer ();
Timer.scheduleatfixedrate (New MyTask (), 1, 10000);
}
Private class MyTask extends TimerTask {
@Override
public void Run () {
Message msg = new Message ();
Msg.what = 1;
Mhandler.sendmessage (msg);
}
}
}
Remember, the processing is in the handlemessage inside, of course, can not, can be in the handler callback method Handlemessage inside. Handler with his callback is also learning, can be said later.
Android View.post (Runnable)