Android Development Note: The difference between Handler runnable and thread

Source: Internet
Author: User
Tags ticket

There are two ways to implement multithreading in Java, one is to inherit the thread class, one to implement the Runnable interface, and the thread class to be defined in the Java.lang package. A class that inherits the thread class to overwrite the run () method in this class can implement multithreaded operations, but only one parent class can inherit from a class, which is the limitation of this method.
Let's look at the example below:

Copy CodeThe code is 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 result is very regular, the first object executes, and then the second object executes, and it does not run against one another. As you can see in the JDK documentation, once the start () method is called, the Run () method is found through the JVM. Starting the Start () method starts the thread:

Copy CodeThe code is 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 not use Start ();
Under the JDK installation path, Src.zip is the entire Java source program, and this code finds the definition of the start () method in thread, and you can see that the private native void Start0 () is used in this method; Where the Native keyword means that the underlying function of the operating system can be called, then such a technique becomes a JNI technology (Java Native Interface)
Runnable interface
In real-world development, a multithreaded operation rarely uses the thread class, but is accomplished through the Runnable interface.

Copy CodeThe code is 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 a subclass defined with runnable, only in the thread class. At this point the thread class is observed, and there is a constructor method: Public Thread (Runnable Targer) This construction method accepts the subclass instance of Runnable, which means that the thread class can be used to start the multithreading of the Runnable implementation. (Start () to coordinate the resources of the system):

Copy CodeThe code is 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 ();
}
}


The difference between the two ways of implementation and contact:
In the development of the program as long as the multithreading must always be implemented runnable interface mainly, because the implementation of the Runnable interface compared to inherit the thread class has the following advantages:
• Avoid the limitations of point inheritance, where a class can inherit multiple interfaces.
• Suitable for sharing of resources
Take the ticket selling procedure as an example, complete by the thread class:

Copy CodeThe code is 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 ("Sell ticket: Ticket" +this.ticket--);
}
}
}
};


Below through three thread objects, while selling tickets:

Copy CodeThe code is 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 sheets, sold 30 tickets.
Mt2.start ();//But actually there are only 10 tickets, and each thread sells its own ticket.
Mt3.start ();//failed to achieve resource sharing
}
}


If you can use runnable to achieve resource sharing, see the example below:

Copy CodeThe code is 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 ("Sell ticket: Ticket" +this.ticket--);
}
}
}
}
Package org.demo.runnable;
public class Runnableticket {
public static void Main (string[] args) {
MyThread mt=new MyThread ();
New Thread (MT). Start ();//the same MT, but not in Thread, if you use the same
New Thread (MT). Start ();//An instantiation of the object Mt will cause an exception
New Thread (MT). Start ();
}
};


Although there are three threads in the program, there are 10 tickets sold, which means that using runnable to achieve multi-threading can achieve the purpose of resource sharing.
connection between Runnable interface and Thread:
public class Thread extends Object implements Runnable
discovers that the thread class is also a subclass of the Runnable interface.
Second:
thread is the system gives you the resources, with the thread you have to get the power to execute the time slice from the CPU, thread does not know your program, not knowing that there is a class such as test, because the sequencer has thousands, Each person's name is different, want to do things are different, so thread only know one! That's runnable. Thread knows runnable and knows there is a run method inside runnable. Once the thread's Start method is called, the run in the Runnable method is automatically run by the thread. So, when we inherit our class (which should be called implementation interface) since runnable, our program belongs to the runnable type. Although it is a subclass of runnable, but people know your father, of course, also knew you. Thread can do whatever your internal situation is, he just has to have the run () method, and he's going to start letting you run it so we can write something in run so that the system runs the code we want to do. Is it very popular and easy to understand? So the steps to run the thread are, 1. Generate our own class object 2. Get thread 3 from the system. Let Threa tune our class object, let it start up code: Test a=new Test (); Thread Thread=new thread (a); Thread needs a parameter, which is your thread class, so that he knows your thread and is eligible to apply to the system to get 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 call method is run in the main thread of the UI:

Copy CodeThe code is 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 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, weThe callback of the message here is an anonymous inner class of runnable
In this case, do not make complex computational logic because it is not used in a new thread.


Four: In the multithreaded programming this piece, we often want to use the Handler,thread and the runnable these three classes, then the relationship between them have you figured out?
First of all, the Android CPU allocation of the smallest unit is a thread, handler is generally created in a line thread, so handler and thread are bound to each other, one by one.
While Runnable is an interface, thread is a subclass of runnable. So, they're both a process.
Handlerthread, as the name implies, is a thread that can handle a message loop, a thread that has looper and can handle the message loop.
Instead of 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 explain:

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


The Java runnable interface requires us to constantly learn the relevant code when it is written. Let's look at how to use the relevant code. The runnable interface has only one method run (), we declare our class implements the Runnable interface and provide this method, and write our thread code into it to complete this part of the task.
But 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 thread class's constructor public thread (Runnable target). Here is an example:

Copy CodeThe code is 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 possible to create an instance of the thread subclass, but it must be noted that the subclass must not overwrite the Run method of the thread class, otherwise the thread will execute the Run method of the subclass, not the run method of the class that we use to implement the Runnable interface. Let's try this one.
Using the Java runnable interface to implement multithreading allows us to accommodate all of the code in a class, and the downside is that we can only use a set of code, and if you want to create multiple threads and have different code for each thread, you still have to create the additional classes, and if so, In most cases, it might not be as compact to inherit the Thread directly from multiple classes.

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.