Android Development: The difference between Handler runnable and thread and the connection application--------------------read this article, from now on!

Source: Internet
Author: User
Tags ticket

http://blog.csdn.net/yanzi1225627/article/details/8582081

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

    1. Package Org.thread.demo;
    2. Public class ThreadDemo01 {
    3. Public static void Main (string[] args) {
    4. MyThread mt1=New MyThread ("Thread A");
    5. MyThread mt2=New MyThread ("thread B");
    6. Mt1.start ();
    7. Mt2.start ();
    8. }
    9. };

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.

    1. Public Interface runnable{
    2. Public void Run ();
    3. }

Example:

  1. Package Org.runnable.demo;
  2. Class MyThread implements runnable{
  3. private String name;
  4. Public MyThread (String name) {
  5. THIS.name = name;
  6. }
  7. Public void Run () {
  8. for (int i=0;i<100;i++) {
  9. System.out.println ("thread start:" +this.name+", i=" +i);
  10. }
  11. }
  12. };

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

  1. Package Org.runnable.demo;
  2. Import Org.runnable.demo.MyThread;
  3. Public class ThreadDemo01 {
  4. Public static void Main (string[] args) {
  5. MyThread mt1=New MyThread ("Thread A");
  6. MyThread mt2=New MyThread ("thread B");
  7. New Thread (MT1). Start ();
  8. New Thread (MT2). Start ();
  9. }
  10. }

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:

  1. Package ORG.DEMO.DFF;
  2. Class MyThread extends thread{
  3. Private int ticket=10;
  4. Public void Run () {
  5. for (int i=0;i<20;i++) {
  6. if (this.ticket>0) {
  7. SYSTEM.OUT.PRINTLN ("Sell ticket: Ticket" +this.ticket--);
  8. }
  9. }
  10. }
  11. };

Below through three thread objects, while selling tickets:

  1. Package ORG.DEMO.DFF;
  2. Public class Threadticket {
  3. Public static void Main (string[] args) {
  4. MyThread mt1=New MyThread ();
  5. MyThread mt2=New MyThread ();
  6. MyThread mt3=New MyThread ();
  7. Mt1.start (); //Each thread sold 10 tickets, and sold a total of 30 votes .
  8. Mt2.start (); //But only 10 tickets are actually sold, each thread sells its own ticket.
  9. Mt3.start (); //Not achieved resource sharing
  10. }
  11. }

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

  1. Package org.demo.runnable;
  2. Class MyThread implements runnable{
  3. Private int ticket=10;
  4. Public void Run () {
  5. for (int i=0;i<20;i++) {
  6. if (this.ticket>0) {
  7. SYSTEM.OUT.PRINTLN ("Sell ticket: Ticket" +this.ticket--);
  8. }
  9. }
  10. }
  11. }
  12. Package org.demo.runnable;
  13. Public class Runnableticket {
  14. Public static void Main (string[] args) {
  15. MyThread mt=New MyThread ();
  16. New Thread (MT). Start (); //The same MT, but not in thread, if you use the same
  17. New Thread (MT). Start (); //Instantiate Object MT, an exception will occur
  18. New Thread (MT). Start ();
  19. }
  20. };

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. 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 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.

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:

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:

1.public class MyThread implements Runnable

0.9

3.int count= 1, number;

4.public MyThread (int num)

5.{

6.numnumber = num;

7.SYSTEM.OUT.PRINTLN ("Create thread" + number);

8.}

9.public void Run ()

10.{

11.while (True)

12.{

13.system.out.println

14. ("Thread" + number + ": Count" + count);

15.if (++count== 6) return;

16.}

17.}

18.public static void Main (String args[])

19.{

20.for (int i = 0; i〈5;

21.i++) New Thread (New MyThread (i+1)). Start ();

22.}

23.}

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.

Reference:

Http://www.cnblogs.com/qingblog/archive/2012/08/08/2628245.html

Http://java.chinaitlab.com/net/807900.html

http://czhjchina.blog.163.com/blog/static/20027904720111153382495/

Http://zhidao.baidu.com/question/82198667.html

Http://developer.51cto.com/art/201203/321042.htm

Android Development: The difference between Handler runnable and thread and the connection application--------------------read this article, from now on!

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.