Android Development Note: The difference between Handler runnable and thread

Source: Internet
Author: User

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:

The code is as follows:
 PackageOrg.thread.demo;classMyThreadextendsthread{PrivateString name; PublicMyThread (String name) {Super(); This. Name =name;}  Public voidrun () { for(inti=0;i<10;i++) {System.out.println ("Thread Start:" + This. name+ ", i=" +i); } } }  PackageOrg.thread.demo; Public classThreadDemo01 { Public Static voidMain (string[] args) {MyThread mt1=NewMyThread ("Thread A"); MyThread mt2=NewMyThread ("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:

The code is as follows:
 Package Org.thread.demo;  Public class ThreadDemo01 {    publicstaticvoid  main (string[] args) {          New MyThread ("Thread A");         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 technology becomes the JNI technology (Java Native Interface) runnable interface in real development a multithreaded operation rarely uses the thread class, Instead, it is done through the Runnable interface.

The code is as follows:
 PackageOrg.runnable.demo; Public InterfaceRunnable { Public voidrun (); classMyThreadImplementsRunnable {PrivateString name;  PublicMyThread (String name) { This. Name =name; }         Public voidrun () { for(inti = 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):

The code is as follows:
 PackageOrg.runnable.demo;ImportOrg.runnable.demo.MyThread; Public classThreadDemo01 { Public Static voidMain (string[] args) {MyThread mt1=NewMyThread ("Thread A"); MyThread mt2=NewMyThread ("Thread B"); NewThread (MT1). Start (); NewThread (MT2). Start (); }}

Two ways of implementation of the difference and connection: 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:

The code is as follows:
 package   ORG.DEMO.DFF;  class  MyThread extends   Thread { private  int  ticket = 10 public  void   run () { for  (int  i = 0; i < 2 0; I++ this . Ticket > 0) {System.out.println ( "Sell ticket: Ticket" + this . Ticket--); }        }    }};

Below through three thread objects, while selling tickets:

The code is as follows:
 PackageORG.DEMO.DFF; Public classThreadticket { Public Static voidMain (string[] args) {MyThread mt1=NewMyThread (); MyThread mt2=NewMyThread (); MyThread Mt3=NewMyThread ();    Mt1.start (); }    //each thread sold a total of 10, sold 30 tickets Mt2.start ();//but actually there are only 10 tickets, and each thread sells its own ticket.//Mt3.start ();//resource sharing not achieved}

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

The code is as follows:
 Packageorg.demo.runnable;classMyThreadImplementsrunnable{Private intticket=10;  Public voidrun () { for(inti=0;i<20;i++){ if( This. ticket>0) {System.out.println ("Sell ticket: Ticket" + This. ticket--); } } } }  Packageorg.demo.runnable; Public classRunnableticket { Public Static voidMain (string[] args) {MyThread Mt=NewMyThread ();NewThread (MT). Start ();//The same MT, but not in thread, if you are using the sameNewThread (MT). Start ();//an instantiated object MT, an exception occursNewThread (MT). Start ();} }; 

Although the program now has three threads, but sold a total of 10 tickets, that is, the use of runnable implementation of multi-threading can achieve the purpose of resource sharing.

Runnable the connection between the interface and the 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 your 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 name is different, want to do things are different, so Thread only knows 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. Build our own class object

2. Get the thread from the system

3. Let Threa tune our class object and let it start up the 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 does not necessarily open a new thread, such as the following method of invocation is run in the main thread of the UI:

The code is as follows:

     Handler mhandler=New  Handler ();      Mhandler.post (new  Runnable () {         publicvoid  run ()         / /         }      });

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'll 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. For example, the code that we see earlier, the callback of our 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:

The code is as follows:
mhandler=New  Handler (); Mhandler.post (new  Runnable () {  void  run () {  // execute code ...   newnew 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:

The code is as follows:
 Public classMyThreadImplementsrunnable{intCount= 1, number; PublicMyThread (intnum) {Numnumber=num; System.out.println ("Create thread" +Number );} Public voidrun () { while(true) {System.out.println ("Thread" + number + ": Count" +count);if(++count== 6)return;}} Public Static voidMain (String args[]) { for(inti = 0; I〈5; I++)NewThread (NewMyThread (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.

Android Development Note: The difference between Handler runnable and thread

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.