The understanding of multithreading in Java

Source: Internet
Author: User
Tags ticket

Goalunderstand the difference between a process and a thread. Master The two implementations of Java threads and their differences. understand the operating state of the thread. Processes and ThreadsDOS system has a very obvious feature, only one virus after the system will immediately panic, because the traditional DOS is a single process processing, so only one program can run, other programs can not run. in Windows systems, even if a virus occurs, the system can still be used, because in Windows it is multi-process processing, there will be multiple programs running at the same time period. threads are actually further divided on the basis of the process, which, from word point of view, can be handled as a process by the spelling checker. Of course there are multiple threads. If a process is missing, the thread will definitely disappear, and if the thread disappears, the process may not disappear. And all threads are concurrent (running) on the basis of the process.
If you run more than one task at a time, all of the system resources will be shared, common to all threads, but the process requires CPU, and traditional single-core CPUs have multiple programs executing at the same time, but only one program can run at the same point in time. This means that all programs have to preempt CPU resources. But now the CPU has grown to a multi-core state, there may be more than one CPU on a computer, then it can be very clear how the multi-threading operation between the concurrent execution. multithreaded implementations of Javain Java, if you want to implement multithreading, you can use the following two ways:inherits the thread class. implements the Runnable interface. Thread classinherit the thread classThe thread class is defined in the Java.lang package as long as a class inherits the thread class, which is called a multithreaded operation class, and in the thread subclass, the Run () method in the thread class must be explicitly covered, and this method is the principal of the thread.
the Java.lang package is automatically imported when the program is run, so there is no need to write import statements manually. once a class inherits the thread class, this class has the ability to operate in multiple threads.
Class MyThread extends thread{//inherits the thread class, as the implementation class of the threads private String name;//indicates the name of the thread public MyThread (String name) {this.name = name;//Configure the Name property by constructing the}public Void Run () {//overwrite the run () method as the thread's action body for (int i=0;i<10;i++) {System.out.println (name + " Run, i = "+ i);}}}; public class Threaddemo01{public static void Main (String args[]) {MyThread MT1 = new MyThread ("Thread A"); Instantiate object MyThread mt2 = new MyThread ("Thread B"); Instantiate object Mt1.run ();//Call Thread principal Mt2.run ();//Call Thread Body}};


from the running results here, there is no looting of resources. The above procedure is to execute a before executing a B, not to achieve the effect of so-called concurrent execution. because the above program is actually called in the ancient form, through the object. method, but if you want to start a thread, you must use the start () method as defined in the thread class. once the start () method is called, the Run () method is actually the final call. The code is as follows:
Class MyThread extends thread{//inherits the thread class, as the implementation class of the threads private String name;//indicates the name of the thread public MyThread (String name) {this.name = name;//Configure the Name property by constructing the}public Void Run () {//overwrite the run () method as the thread's action body for (int i=0;i<10;i++) {System.out.println (name + " Run, i = "+ i);}}}; public class Threaddemo02{public static void Main (String args[]) {MyThread MT1 = new MyThread ("Thread A"); Instantiate object MyThread mt2 = new MyThread ("Thread B"); Instantiate object Mt1.start ();//Call Thread principal Mt2.start ();//Call Thread Body}};

observing the call to start () method really plays the effect of running the program concurrently, which thread grabs the CPU resources and which one runs first. Question 1:Why not call the run () method directly, but instead call it by Start ()? If you want to solve this problem, look at the Java.lang.Thread class and find the definition as follows:
Public synchronized void Start () {        /** * This method was not invoked for the main method thread or "system" * Group THR EADS created/set up by the VM. Any new functionality added * to this method in the future May has to also is added to the  VM. * A Zero status Valu E corresponds to state "NEW".         *        /if (threadstatus! = 0)            throw new Illegalthreadstateexception ();        Group.add (this);        Start0 ();        if (stopbeforestart) {    stop0 (throwablefromstop);}    }
private native void Start0 ();The start () method may throw an exception. Stopbeforestart is a variable of type Boolean. The native keyword represents a keyword that is called by Java to invoke native operating system functions. In Java, a function that runs a Java program calls the native operating system to accomplish a specific function. Proof: If you want to achieve multi-threaded now, it is necessary to support the operating system, because the multithreading operation involved in a preemptive CPU, to wait for the CPU to dispatch, then this must be the underlying operating system support, so the use of native call native system functions, and the multi-threaded implementation of the underlying code in each operating system is certainly different, so using the native keyword can also allow the JVM to automatically adjust the implementation of different JVMs. Threadstatus also represents a state in which the start () method can produce an exception if the thread has already started.
Class MyThread extends thread{//inherits the thread class, as the implementation class of the threads private String name;//indicates the name of the thread public MyThread (String name) {this.name = name;//Configure the Name property by constructing the}public Void Run () {//overwrite the run () method as the thread's action body for (int i=0;i<10;i++) {System.out.println (name + " Run, i = "+ i);}}}; public class Threaddemo03{public static void Main (String args[]) {MyThread MT1 = new MyThread ("Thread A"); Instantiate object Mt1.start ();//Call Thread principal Mt1.start ();//Error}};

runnable InterfaceImplement the Runnable interface: In Java You can also implement multi-threading in a way that implements the Runnable interface, and only an abstract method is defined in the Runnable interface. Public void Run ();multithreading via the Runnable interface:
Class MyThread implements runnable{//implements the Runnable interface as the implementation class of the thread private String name;//indicates the name of the thread public MyThread (String name) { THIS.name = name;//Configure the Name property by constructing a method}public void run () {//overwrite the run () method as the thread's action body for (int i=0;i<10;i++) { SYSTEM.OUT.PRINTLN (name + "Run, I =" + i);}};
If you want to start a thread, you must rely on the thread class, but if you inherited the thread class directly, you can inherit the start () method directly and use it, but there is no such method in the Runnable interface.construction of the thread class:Public Thread (Runnable target);Use the above construction method to start multithreading.
Class MyThread implements runnable{//implements the Runnable interface as the implementation class of the thread private String name;//indicates the name of the thread public MyThread (String name) { THIS.name = name;//Configure the Name property by constructing a method}public void run () {//overwrite the run () method as the thread's action body for (int i=0;i<10;i++) { SYSTEM.OUT.PRINTLN (name + "Run, I =" + i);}}; public class Runnabledemo01{public static void Main (String args[]) {MyThread MT1 = new MyThread ("Thread A"); Instantiate object MyThread mt2 = new MyThread ("Thread B"); Instantiate the object thread t1 = new Thread (MT1);//Instantiate the thread class object thread t2 = new Thread (MT2);//Instantiate the Thread class object T1.start ();//Start Multithreading T2.sta RT ();//Start Multithreading}};


From the program running effect can be found, has completed the multi-threaded function.thread class and Runnable interfacedefinition of the thread class: public class Thread extends Object implements Runnableas you can see from the defined format, the thread class is also a subclass of the Runnable interface.
from the relation of the class, the previous practice is very similar to the proxy design pattern, the thread class completes more operations than the thread principal, for example: allocating CPU resources, judging whether it has been started, and so on. the difference between the thread class and the Runnable interfaceusing the thread class can not achieve the purpose of resource sharing when the operation is multi-threading, while multi-threaded operation using the Runnable interface realizes resource sharing.
Class MyThread extends thread{//inherits the thread class, as the implementation class of the threads private int ticket = 5;//Indicates a total of 5 tickets public void run () {//overwrite the run () method as a thread The operation principal for (int i=0;i<100;i++) {if (this.ticket>0) {System.out.println ("sell ticket: Ticket =" + ticket--);}}}; public class Threaddemo04{public static void Main (String args[]) {MyThread MT1 = new MyThread ();//Instantiation of object MyThread mt2 = NE W MyThread (); Instantiate object MyThread mt3 = new MyThread (); Instantiate the object Mt1.run ();//Call Thread principal Mt2.run ();//Call Thread principal Mt3.run ();//Call Thread Body}};

found that altogether 15 tickets were sold. Proof: Three threads each sell their own tickets, which means that they do not achieve the purpose of sharing resources.because each Mythread object contains its own ticket property. What if I use the Runnable interface now? Also start multiple threads, then all threads will sell a common 5 tickets.
Class MyThread implements runnable{//inherits the thread class, as the implementation class of the threads private int ticket = 5;//Indicates a total of 5 tickets public void run () {//overwrite the Run () method, As the thread's operation principal for (int i=0;i<100;i++) {if (this.ticket>0) {System.out.println ("sell ticket: Ticket =" + ticket--);}}}; public class Runnabledemo02{public static void Main (String args[]) {MyThread MT = new MyThread ();//Instantiate Object New Thread (MT). R Un ();//Call thread principal new Thread (MT). Run ();//Call thread principal new Thread (MT). Run ();//Call Thread Body}};

From the results of the operation, although three threads are now started, but three threads have sold only 5 tickets, to achieve the purpose of resource sharing.the use of thread class and runnable interface conclusionimplementing the Runnable interface has the following obvious advantages over inheriting the thread class:suitable for multiple threads of the same program code to process the same resource. you can avoid the effects of single inheritance limitations. The robustness of the program is enhanced, the code can be shared by multiple threads, and the code is independent of the data. in general, using the Runnable interface in development is the most suitable. the state of the thread:Multithreading also has a fixed state of operation in operation:Create state: A Multithreaded object is ready, thread t = new thread ()ready state: The Start () method is called and waits for the CPU to dispatch. Run state: Executes the Run () method. blocking state: Temporarily stops execution and may give resources to other threads for use. Termination status (dead state): The thread has finished executing and is no longer in use. What is the difference between process hangs, blocking, and sleep? blocking is a process that waits for a resource, but cannot get it right away, must wait for another process to release the resource to continue, the passive cannot get the time slice, and the kernel switches other processes to run. hibernation is generally an active waiver of a CPU time. Hangs is the run time slice, the kernel to dispatch other processes to run, passive loss of CPU.


The understanding of multithreading in Java

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.