The difference between tread class and runnable in multiple threads

Source: Internet
Author: User

I. Difference between the run () method and the Start () method

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:

1  PackageOrg.thread.demo;2 3  Public classMyThreadextendsThread {4     PrivateString name; 5      PublicMyThread (String name) {6         Super(); 7          This. Name =name; 8         }  9          Public voidrun () {Ten          for(inti=0;i<10;i++){   OneSYSTEM.OUT.PRINTLN ("Thread Start:" + This. name+ ", i=" +i);  A         }   -     }   -}
1  PackageOrg.thread.demo;2 3  Public classThreadrundemo {4      Public Static voidMain (string[] args) {5MyThread mt1=NewMyThread ("Thread A"); 6MyThread mt2=NewMyThread ("Thread B"); 7 Mt1.run (); 8 Mt2.run (); 9     }  Ten}

Console

The result is running sequentially , first executing the object, and then the second object executing.

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  PackageOrg.thread.demo;2 3  Public classThreadstartdemo {4      Public Static voidMain (string[] args) {5MyThread mt1=NewMyThread ("Thread A"); 6MyThread mt2=NewMyThread ("Thread B"); 7 Mt1.start (); 8 Mt2.start (); 9     }Ten}

Console

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)

In conclusion, it can be concluded that:

the Start () method is used to start a new thread, and the new thread executes the corresponding run () method. The run () method is just a normal method call, which runs sequentially in the calling thread. 

two. Runnable Interface

In real-world development, a multithreaded operation rarely uses the thread class, but is accomplished through the Runnable interface.

 Public Interface runnable{  publicvoid  run ();  

Example:

1  PackageOrg.runnable.demo; 2  PackageOrg.thread.demo;3 4  Public classMythreadimprunnableImplementsRunnable {5 6     PrivateString name; 7      Publicmythreadimprunnable (String name) {8      This. Name =name; 9     }Ten      One @Override A      Public voidrun () { -          for(inti=0;i<100;i++){   -SYSTEM.OUT.PRINTLN ("Thread Start:" + This. name+ ", i=" +i);  the         }  -     } -}

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  PackageOrg.thread.demo;2 3  Public classRunnabledemo {4      Public Static voidMain (string[] args) {5Mythreadimprunnable mt1=NewMythreadimprunnable ("Thread A"); 6Mythreadimprunnable mt2=NewMythreadimprunnable ("Thread B"); 7         NewThread (MT1). Start (); 8         NewThread (MT2). Start (); 9     }   Ten}

Console

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 limitation of point inheritance, a class can inherit multiple interfaces and realize the sharing of resources.

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

1  PackageOrg.thread.demo;2 3  Public classMyTheard02extendsthread{4     Private intticket=10; 5      Public voidrun () {6          for(inti=0;i<20;i++){  7             if( This. ticket>0){  8SYSTEM.OUT.PRINTLN ("Sell ticket: Ticket" + This. ticket--); 9             }  Ten         }   One     }    A}

Below through three thread objects, while selling tickets:

1  PackageOrg.thread.demo;2  Public classthreadticket{3      Public Static voidMain (string[] args) {4MYTHREAD02 mt1=NewMyThread02 (); 5MYTHREAD02 mt2=NewMyThread02 (); 6MYTHREAD02 mt3=NewMyThread02 (); 7Mt1.start ();//each thread sold a total of 10, and sold 30 tickets .8Mt2.start ();//but actually there are only 10 tickets, and each thread sells its own ticket.9Mt3.start ();//resource sharing not achievedTen     }   One}

Console

Each thread sold 10 sheets, sold 30 tickets, but actually only 10 tickets, each thread sold its own ticket, did not reach the resource sharing

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

1  PackageOrg.thread.demo;2 3  Public classMythread02imprunnableImplementsRunnable {4     Private intticket=10; 5 @Override6      Public voidrun () {7          for(inti=0;i<20;i++){  8             if( This. ticket>0){  9System.out.println ("Sell tickets by implementing Runnable interface: Ticket" + This. ticket--); Ten             }   One         }   A     } -}
1  PackageOrg.thread.demo;2 3  Public classRunnableticket {4       Public Static voidMain (string[] args) {5 6Mythread02imprunnable mt=Newmythread02imprunnable (); 7 8          NewThread (MT). Start ();//The same MT, but not in thread, if you are using the same9          NewThread (MT). Start ();//an instantiated object MT, an exception occursTen          NewThread (MT). Start ();  One     }   A}

Console

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.

The difference between tread class and runnable in multiple threads

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.