Multithreading Thread VS Runnable

Source: Internet
Author: User
Tags ticket

Objective


There are two ways to implement multithreading in Java. The first is the direct inheritance of the thread class, and the second is to implement Runnable interface. So what is the difference between the two ways of implementing multithreading?

To answer this question, we can write a piece of code to analyze. We use the code to simulate the railway ticketing system, to achieve the sale of a day by four ticket sales of a train 100 tickets, a ticket point with a thread.

We begin by writing this procedure:

Class ThreadTest extends thread{    private int ticket = +;    public void Run () {while      (true) {        if (Ticket > 0) {          System.out.println (Thread.CurrentThread (). GetName () +            "is saling ticket" + ticket--);        } else{break;}}}      
Main function test


public class threaddome1{public     static void Main (string[] args) {       threadtest t = new threadtest ();       T.start ();       T.start ();       T.start ();       T.start ();     }   

In the above code, we use the ThreadTest class to simulate the ticket sales process, each cycle of the run method will reduce the total number of votes by 1, simulated sell a ticket, and the car ticket number printed out, directly remaining votes to zero so far. In the main method of the ThreadDemo1 class, we created a thread object and started it repeatedly four times, hoping to generate four threads in this way. Judging from the running results, we found that only one thread was running, and this resulttell us: A thread object can only start a thread, no matter how many times you call the start () method, the result is only one thread.

We then modified the THREADDEMO1 to create four thread objects in the Main method:
public class threaddemo1{public     static void Main (string[] args) {       new ThreadTest (). Start ();       New ThreadTest (). Start ();       New ThreadTest (). Start ();       New ThreadTest (). Start ();     }   }

Class ThreadTest extends thread{    private int ticket = +;    public void Run () {while      (true) {        if (Ticket > 0) {          System.out.println (Thread.CurrentThread (). GetName () +              "is saling ticket" + ticket--);        } else{break;}}}  

Is this the end of the meeting?

The results show that each ticket has been printed four times, i.e.four threads each sell their 100 tickets without selling a common 100 tickets。 How is this situation caused? What we need is that multiple threads deal with the same resource, a resource can only correspond to one object, in the above program, we create four threadtest objects, it is equal to create four resources, each resource has 100 tickets, each thread is working on its own resources.

Through these experiments and analysis, it can be concluded that to achieve this railway ticketing process, we can only create a resource object, but to create multiple threads to process the same resource object, and each thread is running the same program code. Review the process of writing multithreading using interfaces.
    public class threaddemo1{public        static void Main (string[] args) {          threadtest t = new threadtest ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();        }      }  

    Class ThreadTest implements runnable{        Private int tickets = +;        public void Run () {while          (true) {            if (Tickets > 0) {              System.out.println (Thread.CurrentThread (). GetName ( ) +                "is saling ticket" + tickets--);}}}        

In the above program, four threads were created,each thread invokes the run () method in the same ThreadTest object, accessing an instance of a variable (tickets) in the same object, this program has met our needs. You can start multiple Notepad programs on Windows, which means that multiple processes use the same Notepad program code.


It can be seen that implementing the Runnable interface has the following notable benefits over inheriting the thread class:

(1) Suitable for multiple threads of the same program code to handle the same resource situation, the virtual CPU (thread) and the Code of the program, the data effectively separated, better reflect the object-oriented design ideas.

(2) can avoid limitations due to the single inheritance of Java. We often encounter the case that when we want to put a subclass of a class that has been inherited into a multi-threaded, because a class can not have two parent classes at the same time, so can not inherit the thread class, then this class can only adopt the way of implementing the Runnable interface.

(3) It is advantageous to the robustness of the program, the code can be shared by multiple threads, and the code and data are independent. When multiple threads execute code from an instance of the same class, they are said to share the same code. Multiple threads manipulate the same data, regardless of their code. When shared access is the same object, that is, they share the same data. When a thread is constructed, the required code and data are passed in through an object as a constructor argument, an instance of a class that implements the Runnable interface.

Multithreading Thread VS Runnable

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.