Java Create multithreading (reprint)

Source: Internet
Author: User
Tags thread class ticket

Reprinted from: Java Two ways to create a thread

Java provides threading class thread to create multithreaded programs. In fact, creating a thread is the same as creating an object of a normal class, and a thread is an instance object of the thread class or its subclasses. Each thread object describes a separate thread. To produce a thread, there are two ways of doing it:

You need to derive a new thread class from the Java.lang.Thread class, overloading its run () method;
Implement the Runnalbe interface, overloading the run () method in the Runnalbe interface.

Why should Java provide two ways to create threads? What are the differences between them? In comparison, which method is better?

In Java, a class only supports single inheritance, that is, when a new class is defined, it can only extend one external class. This way, if the custom thread class is created by extending the thread class, then the custom class cannot extend the other classes. It is not possible to implement more complex functions. Therefore, if your custom class must extend other classes, you can define the class as a threading class by using a method that implements the Runnable interface, which avoids the limitations of Java single inheritance.

It is also important that threads created with the implementation of the Runnable interface can handle the same resource, thus sharing resources.

(1) Creating multithreading by extending the thread class

Suppose a cinema has three ticket outlets for ticketing for children, adults and the elderly, respectively. The cinema has 100 movie tickets for each window, namely children's, adult and senior. Three windows need to sell tickets at the same time, and now there is only one conductor, the conductor is equivalent to a CPU, three Windows is equivalent to three threads. The program looks at how to create these three threads.

12345678910111213141516171819202122 <span style="font-size: 16px;">publicclassMutliThreadDemo {    publicstaticvoidmain(String [] args){        MutliThread m1=new MutliThread("Window 1");        MutliThread m2=newMutliThread("Window 2");        MutliThread m3=newMutliThread("Window 3");        m1.start();        m2.start();        m3.start();    }}classMutliThread extendsThread{    privateintticket=100;//每个线程都拥有100张票    MutliThread(String name){        super(name);//调用父类带参数的构造方法    }    public voidrun(){        while(ticket>0){            System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());        }    }}</span>

A thread class is defined in the program, which extends the thread class. The extended thread class is used to create three thread objects in the main method of the Mutlithreaddemo class and to start them separately through the start () method.

As you can see from the results, each thread corresponds to 100 movie tickets, and there is no relationship between them, which means that each thread is equal, has no priority relationship, and therefore has the opportunity to get CPU processing. However, the results show that the three threads are not alternately executed sequentially, but in the case of three threads being executed at the same time, some threads are given more chances of being allocated the times, the tickets are sold in advance, and some threads are given less opportunity to allocate time slices, and the tickets are sold out later.

It can be seen that multiple threads created with the extended thread class, although executing the same code, are independent of each other and have their own resources, without interfering with each other.

(2) Create multithreading by implementing the Runnable interface

1234567891011121314151617181920212223242526 <span style="font-size: 16px;">public classMutliThreadDemo2 {    publicstaticvoidmain(String [] args){        MutliThread m1=newMutliThread("Window 1");        MutliThread m2=newMutliThread("Window 2");        MutliThread m3=newMutliThread("Window 3");        Thread t1=newThread(m1);        Thread t2=newThread(m2);        Thread t3=newThread(m3);        t1.start();        t2.start();        t3.start();    }}classMutliThread implementsRunnable{    privateintticket=100;//每个线程都拥有100张票    private String name;    MutliThread(String name){        this.name=name;    }    publicvoidrun(){        while(ticket>0){            System.out.println(ticket--+" is saled by "+name);        }    }}</span>

Since these three threads are also independent of each other and have their own resources, that is, 100 movie tickets, the results of the program output and (1) result in a similar light. are the respective threads of their own 100 tickets for separate processing, non-impact.

Visible, as long as the reality of the situation requires that new threads are independent of each other, each with resources, and do not interfere with each other, which way to create multi-threading is possible. Because multi-threaded threads created in both ways can achieve the same functionality.

Since these three threads are independent of each other and have their own resources, i.e. 100 movie tickets, the results of the program output are similar to those of the example 4.2.1. are the respective threads of their own 100 tickets for separate processing, non-impact.

Visible, as long as the reality of the situation requires that new threads are independent of each other, each with resources, and do not interfere with each other, which way to create multi-threading is possible. Because multi-threaded threads created in both ways can achieve the same functionality.

(3) Realize the resource sharing between threads by implementing Runnable interface

In reality, there are situations, such as simulating a train station ticketing system, if the day from A to B to the train ticket only 100, and allow all windows to sell the 100 tickets, then each window is equivalent to a thread, But the difference between this and the previous example is that all the threads are working on the same resource, which is 100 tickets. If you are still using the previous method to create a thread that is obviously impossible to implement, how do you deal with this situation? Look at the following program, the program code is as follows:

1234567891011121314151617181920 <span style="font-size: 16px;">publicclassMutliThreadDemo3 {    publicstaticvoidmain(String [] args){        MutliThread m=newMutliThread();        Thread t1=newThread(m,"Window 1");        Thread t2=newThread(m,"Window 2");        Thread t3=newThread(m,"Window 3");        t1.start();        t2.start();        t3.start();    }}classMutliThread implementsRunnable{    privateintticket=100;//每个线程都拥有100张票    publicvoidrun(){        while(ticket>0){            System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());        }    }}</span>

The result, as previously analyzed, is that the program creates only one resource in memory, and the new three threads are based on access to the same resource, and because the same code is running on each thread, they perform the same function.

It can be seen that if a real-world problem requires that multiple threads be created to perform the same task, and that the same resource will be shared among the multiple threads, the multithreaded program could be created in a way that implements the Runnable interface. This functionality is not possible by extending the thread class, and the reader wants to see why.

The implementation of the Runnable interface has unparalleled advantages over the extended thread class. This approach is not only beneficial to the robustness of the program, so that the code can be shared by multiple threads, and the code and data resources are relatively independent, which is particularly suitable for multiple threads with the same code to handle the same resource situation. In this way, the thread, code and data resources are effectively separated, which embodies the idea of object-oriented programming. As a result, almost all multithreaded programs are done by implementing the Runnable interface.

Java Create multithreading (reprint)

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.