Java multithreaded Learning (verbose)

Source: Internet
Author: User

The difference between a process and a thread

Process: Each process has its own code and data space (process context), and there is a significant overhead of switching between processes, and a process contains 1--n threads. (Process is the smallest unit of resource allocation)

Threads: The same class of threads share code and data space, each thread has a separate run stack and program counter (PC), and thread switching overhead is small. (Thread is the smallest unit of CPU scheduling)

Threads and processes are divided into five phases: Create, ready, run, block, terminate.

Multi-process means that the operating system can run multiple tasks (programs) at the same time.

Multithreading refers to the execution of multiple sequential streams in the same program.

In Java to implement multi-threading, there are two means, one is to continue the thread class, the other is to implement the Runable interface (in fact, there should be three, there is a realization of the callable interface, and with the future, the thread pool used)

Second, expand the Java.lang.Thread class

 Packagecom.multithread.learning; /*** @functon Multi-threaded Learning *@authorGeorge93 * @time 2017.6.7*/  classThread1extendsthread{PrivateString name;  PublicThread1 (String name) { This. name=name; }       Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run:" +i); Try{sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }          }               }  }   Public classMain { Public Static voidMain (string[] args) {Thread1 mTh1=NewThread1 ("A"); Thread1 MTH2=NewThread1 ("B");          Mth1.start ();        Mth2.start (); }    }  
Description: When the program starts running main, the Java Virtual machine starts a process, and the main thread is created at the main () call. With the Start method of the two objects that call Mitisay, another two threads are also started, so that the entire application runs under multiple threads.        Note: Instead of executing multithreaded code immediately after the call to the start () method, the thread becomes operational (Runnable) and when it is run is determined by the operating system. The purpose of the Thread.Sleep () method call is to not allow the current thread to occupy the CPU resources acquired by the process alone to allow a certain amount of time for other threads to execute. Second, realize java.lang.Runnable interfacethe use of runnable is also a very common one, we just need to rewrite the Run method to
/*** @functon Multi-threaded Learning *@authorGeorge93 * @time 2017.6.7*/   Packagecom.multithread.runnable; classThread2Implementsrunnable{PrivateString name;  PublicThread2 (String name) { This. name=name; } @Override Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run:" +i); Try{Thread.Sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }              }                }        }   Public classMain { Public Static voidMain (string[] args) {NewThread (NewThread2 ("C") . Start (); NewThread (NewThread2 ("D") . Start (); }    }  
Description: By implementing the Runnable interface, the Thread2 class has the characteristics of multithreaded classes. The run () method is a convention for multi-threaded procedures. All multithreaded code is inside the Run method. Three, the difference between thread and runnableif a class inherits the thread, it is not suitable for resource sharing. However, if the Runable interface is implemented, it is easy to realize the resource sharing.

Summarize:

The benefits of implementing the Runnable interface are more than inheriting the thread class:

1): Suitable for multiple threads of the same program code to process the same resource

2): Can avoid the restriction of single inheritance in Java

3): Increase the robustness of the program, the code can be shared by multiple threads, code and data Independent

4): The thread pool can only be put into a class that implements runable or callable classes and cannot be placed directly into the inherited thread

Add: In Java, you start at least 2 threads per program run. One is the main thread and one is the garbage collection thread. Because every time a class is executed with a Java command, a JVM is actually started, and each JVM internship starts a process in the operating system. In Java so the threads are all started at the same time, as to when, which first executes, fully see who first get the CPU resources. Reference: https://yq.aliyun.com/articles/77972

Java multithreaded Learning (verbose)

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.