The difference between handler runnable and thread in Android

Source: Internet
Author: User
Tags message queue

Original link: http://www.codeceo.com/article/android-handler-runnable-thread.html

Handler in Android can control runnable asynchronously, so what's the difference between this and the thread in Android? This article will explain this issue through a number of angles, read this article, I believe you will have a very comprehensive understanding of the handler runnable and thread in Android.

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:

Package Org.thread.demo; Class MyThread extends thread{private string name; public MyThread (String name) {super (); this.name = name;} public Voi D 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:

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.

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):

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:

    • To avoid the limitations of point inheritance, a class can inherit multiple interfaces.
    • Resource-friendly sharing

Take the ticket selling procedure as an example, complete by the thread class:

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:

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 only 10 tickets, each thread sold its own ticket  mt3.start ();//did not achieve resource sharing  }  }

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

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 are using the same new thread (MT). Start ();//An instance of the object MT, the exception new thread (MT) appears. 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 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 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 interpretation of this method is as follows:" The runnable would be run on the user interface thread. The

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.

Fourth: 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:

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 thread thread = new Thread ();  Thread.Start ();  Handlerthread thread = new Handlerthread ("string"); Thread.Start ();

Fifth: The Java runnable interface requires us to constantly learn the relevant code as 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:

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.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The difference between handler runnable and thread in Android

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.