Comparison of two ways to implement Java multithreading

Source: Internet
Author: User

Comparison of two ways to implement Java multithreading
One, direct inheritance thread class
The difference between two ways to realize the Runnable interface of thread class

For example, the ticket office has four windows, can be sold one day a list of 100 tickets, at this time, 100 tickets can be considered as a shared resource, four ticketing windows need to create four threads
You can get the instance object of the current thread through the thread's CurrentThread () method, and then call the GetName () method to get the thread's name inheritance thread class and implement multithreading

Example, Example04.java

public class example04{public
    static void Main (string[] args) {
        new Ticketwindow (). Start ();     Creates a thread object Ticketwindows and opens the
        new Ticketwindow (). Start ();     Creates a thread object Ticketwindows and opens the
        new Ticketwindow (). Start ();     Creates a thread object Ticketwindows and opens the
        new Ticketwindow (). Start ();     Create a Thread object Ticketwindows and turn on
    }
}
class Ticketwindow extends thread{
    private int tickets=100;
    public void Run () {//
        pass dead Loop statement, print statement while
        (true) {
            if (tickets>0) {
                //Get current thread
                ///Get current thread name
                Thread th=thread.currentthread ();
                String th_name=th.getname ();
                System.out.println (th_name+ "is on sale" +tickets--+ "Ticket");}
            }

Compile run

As you can see, each ticket is printed four times.
The reason, four threads did not share 100 tickets, but each sold 100 tickets
Creating four Ticketwindow objects in your program equals creating four ticketing programs, each with 100 tickets, each of which handles its own resources independently

Note that each thread has its own name, the main thread default name is main, the user creates the default name of the first Thread-0, the second thread's default name is Thread-1, and so on, if you want to specify the name of the thread, you can call SetName by calling the String name) to set the name for the thread

Because, in the real life, the ticket resources in the system are shared, obviously the above operation result is unreasonable
In order to ensure the sharing of resources, in the program can only create a ticket object, and then, to open a number of threads to run the same ticket ticketing method, in simple terms, is four threads running the same ticket procedures, at this time, it is necessary to use the second implementation of the thread to implement the runnable interface,

Example, Example05.java

public class example05{public
    static void Main (string[] args) {
        Ticketwindow tw=new ticketwindow ();
        New Thread (TW, Window 1). Start ();       Creates a thread object, named Window 1, which opens thread
        new threads (TW, Window 2). Start ();       Creates a thread object, named Window 2, which opens thread
        new threads (TW, Window 3). Start ();       Creates a thread object, named Window 3, which opens thread
        new threads (TW, Window 4). Start ();       Create the thread object and name it window 4, open the thread
    }
}
class Ticketwindow implements runnable{
    private int tickets=100;
    public void Run () {while
        (true) {
            if (tickets>0) {
                //Get current thread
                //expiratory current thread name thread
                th= Thread.CurrentThread ();
                String th_name=th.getname ();
                System.out.println (th_name+ "is on sale" +tickets--+ "Ticket");}
            }

Compile run

Code description
Only one Ticketwindow object is created, then four threads are created, and the Run () method in the Ticketwindow object is invoked on each thread, so that four threads are guaranteed access to the same tickets variable and 100 tickets are shared.

As you can see, implementing the Runnable interface is as advantageous as the inheritance thread class

1, suitable for multiple threads of the same program code, to deal with the situation of the same resource, the thread with the program code, data effective separation, a good embodiment of the object-oriented design idea

2, can avoid because of Java single inheritance, the limitations brought by
In a program, this situation is often encountered by using a subclass that has inherited a class, creating a thread, because a class cannot have two parent classes at the same time, so you cannot inherit the thread class, so you can only implement the Runnable interface

In practice, most applications will implement the Runnable interface to create multithreaded

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.