There are two ways to implement multithreading in Java and the difference between the two ways

Source: Internet
Author: User
Tags ticket

the internet is widely circulated is an online ticketing system to explain. Forwarded over. I don't know where the original text is from .

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:

Java code 650) this.width=650; "src=" Http://yuelangyc.iteye.com/images/icon_star.png "alt=" collection Code "style=" margin:0px; Padding:0px;border:0px;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

  1. class ThreadTest extends thread{

  2. Private int ticket = +;

  3. Public void Run () {

  4. while (true) {

  5. if (Ticket > 0) {

  6. System.out.println (Thread.CurrentThread (). GetName () +

  7. "is saling ticket" + ticket--);

  8. }Else{

  9. break;

  10. }

  11. }

  12. }

  13. }


main test class:

Java code 650) this.width=650; "src=" Http://yuelangyc.iteye.com/images/icon_star.png "alt=" collection Code "style=" margin:0px; Padding:0px;border:0px;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

  1. Public class threaddome1{

  2. Public Static void Main (string[] args) {

  3. ThreadTest t = new threadtest ();

  4. T.start ();

  5. T.start ();

  6. T.start ();

  7. T.start ();

  8. }

  9. }


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. From the running results we found that only one thread is running, the result tells 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:

Java code 650) this.width=650; "src=" Http://yuelangyc.iteye.com/images/icon_star.png "alt=" collection Code "style=" margin:0px; Padding:0px;border:0px;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

  1. Public class threaddemo1{

  2. Public Static void Main (string[] args) {

  3. New ThreadTest (). Start ();

  4. New ThreadTest (). Start ();

  5. New ThreadTest (). Start ();

  6. New ThreadTest (). Start ();

  7. }

  8. }


Java code 650) this.width=650; "src=" Http://yuelangyc.iteye.com/images/icon_star.png "alt=" collection Code "style=" margin:0px; Padding:0px;border:0px;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

  1. class ThreadTest extends thread{

  2. Private int ticket = +;

  3. Public void Run () {

  4. while (true) {

  5. if (Ticket > 0) {

  6. System.out.println (Thread.CurrentThread (). GetName () +

  7. "is saling ticket" + ticket--);

  8. }Else{

  9. break;

  10. }

  11. }

  12. }

  13. }



Is this the end of the meeting?

The results show that each ticket is printed four times, that is, four threads each sell their own 100 tickets, instead of 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.

Java code 650) this.width=650; "src=" Http://yuelangyc.iteye.com/images/icon_star.png "alt=" collection Code "style=" margin:0px; Padding:0px;border:0px;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

  1. Public class threaddemo1{

  2. Public Static void Main (string[] args) {

  3. ThreadTest t = new threadtest ();

  4. New Thread (t). Start ();

  5. New Thread (t). Start ();

  6. New Thread (t). Start ();

  7. New Thread (t). Start ();

  8. }

  9. }


Java code 650) this.width=650; "src=" Http://yuelangyc.iteye.com/images/icon_star.png "alt=" collection Code "style=" margin:0px; Padding:0px;border:0px;background:rgb (244,247,249) None repeat scroll 0px 0px; "/>

  1. class ThreadTest implements runnable{

  2. Private int tickets = +;

  3. Public void Run () {

  4. while (true) {

  5. if (Tickets > 0) {

  6. System.out.println (Thread.CurrentThread (). GetName () +

  7. "is saling ticket" + tickets--);

  8. }

  9. }

  10. }

  11. }



in the above program, four threads were created, each calling the run () method in the same ThreadTest object, accessing an instance of the variable (tickets) in the same object, which satisfies 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.


This article is from the "No Water Fish" blog, please be sure to keep this source http://javaqun.blog.51cto.com/10687700/1703190

There are two ways to implement multithreading in Java and the difference between the two ways

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.