Android Development notes: The difference between Handler runnable and thread is detailed _android

Source: Internet
Author: User
Tags message queue thread class ticket
There are two ways to implement multithreading in Java, one is to inherit the thread class, the other is to implement the Runnable interface; the thread class is defined in the Java.lang package. A class can implement multithreading as long as it inherits the thread class while it is overridden by the run () method in this class, but a class can inherit only one parent class, which is the limitation of this method.
Here's a look at the example:
Copy Code code as follows:

Package Org.thread.demo;
Class Mythread extends thread{
private String name;
Public Mythread (String name) {
Super ();
THIS.name = name;
}
public void Run () {
for (int i=0;i<10;i++) {
SYSTEM.OUT.PRINTLN ("Thread Start:" +this.name+ ", i=" +i);
}
}
}
Package Org.thread.demo;
public class ThreadDemo01 {
public static void Main (string[] args) {
Mythread mt1=new mythread ("Thread A");
Mythread mt2=new mythread ("thread B");
Mt1.run ();
Mt2.run ();
}
}

However, the results are very regular, first the first object executes, then the second object executes, and does not run with each other. As you can see in the JDK documentation, once the start () method is invoked, the run () method is found through the JVM. The start Start () method starts the thread below:
Copy Code code as follows:

Package Org.thread.demo;
public class ThreadDemo01 {
public static void Main (string[] args) {
Mythread mt1=new mythread ("Thread A");
Mythread mt2=new mythread ("thread B");
Mt1.start ();
Mt2.start ();
}
};

This allows the program to complete the interactive operation normally. So why do you have to use the start () method to start multithreading?
Under the JDK installation path, Src.zip is the entire Java source program, which finds the definition of the start () method in thread, and discovers that the private native void Start0 () is used in this method; Where the Native keyword indicates that the underlying function of the operating system can be invoked, such technology becomes JNI technology (Java Native Interface)
runnable Interface
In actual development, a multithreaded operation rarely uses the thread class, but is done through the Runnable interface.
Copy Code code as follows:

public interface runnable{
public void run ();
}
Example:
Package Org.runnable.demo;
Class Mythread implements runnable{
private String name;
Public Mythread (String name) {
THIS.name = name;
}
public void Run () {
for (int i=0;i<100;i++) {
SYSTEM.OUT.PRINTLN ("Thread Start:" +this.name+ ", i=" +i);
}
}
};

However, there is no start () method in subclasses that are defined using runnable, only in the thread class. The thread class is observed at this time, and there is a construction method: Public Thread (Runnable Targer) This constructor accepts the subclass instance of Runnable, that is, the thread class can be used to start the multithreading of Runnable implementations. (Start () can coordinate the system's resources):
Copy Code code as follows:

Package Org.runnable.demo;
Import Org.runnable.demo.MyThread;
public class ThreadDemo01 {
public static void Main (string[] args) {
Mythread mt1=new mythread ("Thread A");
Mythread mt2=new mythread ("thread B");
New Thread (MT1). Start ();
New Thread (MT2). Start ();
}
}

two ways to achieve differences and relationships:
In program development as long as multithreading is definitely always to implement the Runnable interface, because the implementation of the Runnable interface compared to the inheritance of the thread class has the following advantages:
• Avoid the limitations of point inheritance, a class can inherit multiple interfaces.
• Resource-appropriate sharing
Take the ticket-selling procedure as an example, through the thread class to complete:
Copy Code code as follows:

Package ORG.DEMO.DFF;
Class Mythread extends thread{
private int ticket=10;
public void Run () {
for (int i=0;i<20;i++) {
if (this.ticket>0) {
System.out.println ("Selling Tickets: Ticket" +this.ticket--);
}
}
}
};

The following three thread objects, while selling tickets:
Copy Code code as follows:

Package ORG.DEMO.DFF;
public class Threadticket {
public static void Main (string[] args) {
Mythread mt1=new mythread ();
Mythread mt2=new mythread ();
Mythread mt3=new mythread ();
Mt1.start ()//each thread sold 10 pieces each, sold a total of 30 tickets
Mt2.start ()//But actually there are only 10 tickets, each thread sells its own ticket
Mt3.start ()//does not meet resource share
}
}

If you can implement resource sharing with runnable, here's an example:
Copy Code code as follows:

Package org.demo.runnable;
Class Mythread implements runnable{
private int ticket=10;
public void Run () {
for (int i=0;i<20;i++) {
if (this.ticket>0) {
System.out.println ("Selling Tickets: Ticket" +this.ticket--);
}
}
}
}
Package org.demo.runnable;
public class Runnableticket {
public static void Main (string[] args) {
Mythread mt=new mythread ();
New Thread (MT). Start ();//same MT, but not in Thread, if you use the same
New Thread (MT). Start ()///The instantiated object MT, an exception is found
New Thread (MT). Start ();
}
};

Although there are now three threads in the program, but sold a total of 10 tickets, that is, using runnable to achieve the goal of sharing resources.
The connection between runnable interface and thread:
Public class Thread extends Object implements Runnable
found that the thread class is also a subclass of the Runnable interface.
Second:
Thread is the system to give you the resources, with thread you can get from the CPU to execute the time slice of the power, thread does not know your program, do not have the test class, because the thousands, each name is different, want to do things are different, so Thread only knows one! That's runnable. Thread knew Runnable and knew that Runnable had a run method inside it. Once the thread's Start method is invoked, run in the Runnable method is automatically run by thread. So, when we inherit our classes (which should be called implementing interfaces) since Runnable, our program belongs to the runnable type. Although it is a runnable, but people know your father, of course, you. Thread can do whatever is inside you, he just wants you to have the run (), and he's going to start letting you run, so let's write something in run so we can get the system running the code we want to do. Is it very popular and easy to understand? So the step to run the thread is, 1. Generate our own class object 2. Get thread 3 from the system. Let Threa our class object and let it start code: Test a=new Test (); Thread Thread=new thread (a); Thread needs a parameter, that is, you make up the threading class, so he knows your thread, also eligible to apply to the system to get the CPU time slice thread.start (); You can simply write: New Thread (a). Start ();
Third:
Runnable is not necessarily a new thread, such as the following invocation method is run in the UI main thread:
Copy Code code as follows:

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 be added to the message queue. The runnable is 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 runnable subclass) by calling the handler post method, and handler will invoke the Looper run method execution in runnable.
Runnable is an interface, not a thread, and a generic thread implements Runnable. So if we use anonymous inner classes that are run on the UI main thread, if we use the thread class that implements this runnable interface, then it runs 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 handler. In handler, it wraps the action object passed over into a message (the callback of messages is action) and puts it into the UI thread's messaging loop. When handler processes the message again, a branch (the one that is not explained) is set up for it, calling the runnable run method directly. At this point, it has been routed to the UI thread, so we can update the UI without any hesitation.
The following figure, the code we saw earlier, we The callback of the message here is a runnable anonymous inner class
In this case, because it is not used in a new thread, you should never do complex computational logic.

View.post(Runnable )" border="0" alt="image" src="yun_qi_img/201305281015122.png" width="687" height="444">


Four: In multithreaded programming this piece, we often have to use the Handler,thread and runnable these three classes, then the relationship between them do you understand?
First of all, the Android CPU allocation of the smallest unit is a thread, handler is generally in a line Chengri created, so handler and thread is mutually binding, one by one corresponds.
And Runnable is an interface, thread is a runnable subclass. So, they're both a process.
Handlerthread, as its name suggests, is a thread that can handle the message loop, a thread with a looper that can handle message loops.
Rather than handler and a thread binding, it is better to say that handler is corresponding to Looper one by one.
Finally, in the UI thread (the main thread), you need to say:
Copy Code code as follows:

Mhandler=new Handler ();
Mhandler.post (New Runnable () {
void Run () {
Execute code ...
}
});
This thread actually runs within the UI thread and does not have a new thread.
The common way to create new threads is to:
Thread thread = new Thread ();
Thread.Start ();
Handlerthread thread = new Handlerthread ("string");
Thread.Start ();

V: Java runnable interface in the relevant writing needs us to continue to learn the relevant code. Let's look at how to use the relevant code. The runnable interface has only one method run (), and we complete this part by declaring our class implements the Runnable interface and providing this method to write our thread code into it.
However, the Runnable interface does not have any support for threading, and we must also create an instance of the thread class, which is implemented by the constructor of the thread class, public thread (Runnable target). Here is an example:
Copy Code code as follows:

public class Mythread implements Runnable
{
int count= 1, number;
public mythread (int num)
{
Numnumber = num;
SYSTEM.OUT.PRINTLN ("Create thread" + number);
}
public void Run ()
{
while (true)
{
System.out.println
("thread" + number + ": Count" + count);
if (++count== 6) return;
}
}
public static void Main (String args[])
{
for (int i = 0; i〈5;
i++) New Thread (New Mythread (i+1)). Start ();
}
}

Strictly speaking, it is also possible to create an instance of the thread subclass, but it must be noted that the subclass must not overwrite the thread class's Run method, otherwise the thread will execute the subclass's Run method rather than the run method of the class we use to implement the Runnable interface. You may wish to try it out.
Using the Java runnable interface to implement multithreading allows us to include all the code in a class, which is good for encapsulation, and its disadvantage is that we can only use a single set of code, and if you want to create multiple threads and have different code for each thread, you still have to create a class, if so, In most cases, it might not be as easy to inherit Thread directly from multiple classes.
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.