Two basic implementation frameworks of "Java multithreading"

Source: Internet
Author: User
Tags ticket

Java Multi-threaded learning two basic framework of implementation First, preface

When a Java program starts, a thread starts immediately, and the program is often called the main thread of the program. All other sub-threads are generated by the main thread. The main thread is executed at the beginning of the program, and the program ends with the end of the main thread.

Java writers run in the Java Virtual Machine (JVM), and within the JVM, the multitasking of the program is done through threads. Starting a Java application with Java commands starts a JVM process. In the same JVM process, there is only one process, which is itself. In this JVM environment, all program code runs as threads.

second, the concept of multithreading

Usually, the simple program we touch is single-threaded, but if we need to do "multi-line operation", we need to use multi-threading, for a process of multiple threads to say, more than one thread to share the process of memory block, when a new thread is generated, the operating system does not allocate new memory, Instead, let the new thread share the memory of the original process block. As a result, communication between threads is easy and fast. Because different processes are in different chunks of memory, communication between processes is relatively difficult.

In Java, there are two ways to implement multithreading: Inherit the Java.lang.Thread class, and implement the Java.lang.Runnable interface.

third, inherit the thread class to realize multithreading

When a class inherits the thread class, the run () method must be overloaded in the class, and the run () method is the entry for the thread, and in the process of invocation, the new thread is started by invoking the start () method, whose basic framework is:

1 classClass nameextendsthread{2 Method 1;3 Method 2;4 ... ..5  Public voidrun () {6 //Other code ...7 }8 attribute 1;9 attribute 2;Ten ... .. One   A}

Here, we use a simple window to buy tickets for example to achieve this kind of multithreading

1 classTestthreadextendsThread2 {3     PrivateString name;4      PublicTestthread (String name)5     {6          This. name=name;7     }8      Public voidRun ()9     {Ten  One          for(inti = 0; I < 7; i++) A         { -             if(num > 0) -             { theSystem.out.println (name+ "Selling tickets" + "num=" + num--); -             } -         } -     } +  -  +      Public Static voidMain (string[] args) A     { at  -Testthread H1 =NewTestthread ("Windows 1"); -Testthread H2 =NewTestthread ("Windows 2"); -Testthread H3 =NewTestthread ("Windows 3"); - H1.start (); - H2.start (); in H3.start (); -     } to  +     Private intnum = 5; -}

in this simple example, it is clear to see that the implementation of threads implementing multithreading has been called, in this case the result is:

1 window 1 is selling tickets  num= 5 2 window 1 is selling tickets  num= 4 3 window 1 is selling tickets  num= 3 4 window 1 is selling tickets  num= 2 5 window 1 is selling tickets  num= 1 6 window 2 is selling the ticket  nu m= 5 7 window 2 is selling tickets  num= 4 8 window 2 is selling tickets  num= 3 9 window 2 is selling tickets  num= 210 window 2 is selling tickets  num= 111 window 3 is selling tickets  num= 512 window 3 is Sell tickets  num= 413 window 3 is selling tickets  num= 314 window 3 is selling tickets  num= 215 window 3 is selling tickets  num= 1

and this result has some unpredictability, we can not determine the specific order of execution between threads, at the same time, more importantly, through the inheritance thread implementation of multithreading can not achieve the sharing of resources to buy tickets as an example, assuming that the total number of votes is 5, We can only sell these 5 tickets through a window, or we open three windows, but this three window has 5 tickets, which is obviously a bit different from our design philosophy. So, when implementing multithreading, I prefer to use the method of implementing the Runnable interface.

implement runnable interface to realize multithreading

similar to inheriting the thread, when a class implements the Runnable interface, the run () method must also be overloaded in the class, and the run () method is also the entry for the thread, which, in the process of invocation, initiates a new thread by invoking the start () method, whose basic framework is:

1 classClass nameImplementsrunnable{2 Method 1;3 Method 2;4 ... ..5  Public voidrun () {6 //Other code ...7 }8 attribute 1;9 attribute 2;Ten ... .. One   A}

There will be a slight difference in the call, or a simple window ticket to illustrate:

1 classMyThreadImplementsRunnable2 {3  4     Private intTicket = 5;//5 Tickets5  6      Public voidRun ()7     {8          for(inti=0; i<=20; i++) 9         {Ten             if( This. ticket > 0)  One             { ASystem.out.println (Thread.CurrentThread (). GetName () + "Selling tickets" + This. ticket--); -             } -         } the     } - } -  Public classTestthread { -       +      Public Static voidmain (String [] args) -     { +MyThread my =NewMyThread (); A         NewThread (My, Window No. 1th)). Start (); at         NewThread (My, Window No. 2nd)). Start (); -         NewThread (My, Window No. 3rd)). Start (); -     } -}

the results of the program execution are:

1 No. 1th window is selling tickets 52 1th window is selling tickets 43 1th window is selling tickets 34 2nd window is selling tickets 25 1th window is selling tickets 1

So, we see our pre-set effect, that is, through the implementation of the Runnable interface method, we realize the sharing of resources.

v. Summary

When inheriting the thread class to implement multi-threading, we created three different objects, so the three threads that were created were actually three different tasks to complete, so they were done independently of each other, and by implementing the Runable interface to implement multithreading, we created only one object, Then instantiate three different threads to accomplish this task, so the equivalent is to accomplish the task together.

In fact, the thread class is also implemented Runnable interface, its source code is as follows:

1 classThreadImplementsRunnable {2     //... ..3  Public voidrun () {4         if(Target! =NULL) {5 Target.run ();6         }7         }8}

The run method in thread is actually called the Run method of the Runnable interface. The method is dead, the person is alive, the concrete use, may according to the actual situation to choose. If a class inherits the Thread, it is not suitable for resource sharing. But if the runable interface is implemented, it breaks through the restriction of single inheritance in Java, and it is easy to realize resource sharing.

Multithreading is a very important part of Java, this article only involves the most basic implementation of multithreading and the part of the call, such as two examples of the operation may involve synchronization problems, running results may be some discrepancy, in the future will continue to update some in-depth things, hope to be able to help later learners.

Reference:http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html

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.