One of the key features of Java is the internal support for multi-threading, a series of articles that will detail the basics of Java Multi-threading
Multithreading Overview
Multithreading Introduction
- The program has only one execution flow, so such a program is a single threaded procedure.
- If a program has multiple execution processes, then the program is a multithreaded program.
Process: A running program that is a separate unit for resource allocation and invocation by the system. Each process has its own memory space and system resources.
Thread: is a single sequential control flow in a process and is an execution path. A process, if there is only one execution path, is called a single-threaded procedure.
A process that has multiple execution paths is called a multithreaded program.
How Java programs work
The Java command launches the Java Virtual machine, starting the JVM, which is equivalent to launching an application, that is, initiating a process. The process automatically starts a "main thread" and then the main thread calls the main method of a class. So the main method runs in the main thread. All programs prior to this are single-threaded.
The Java Virtual machine is multithreaded because there are garbage collection threads in addition to the main thread
Multithreading implementation Scenarios
Mode 1: Inherit the thread class
Steps
1, the custom class Mythread inherits the thread class.
2, Mythread class inside rewrite run ()
3. Create objects
4. Start thread
The following code:
/** This class is going to rewrite the run () method, why? * not all code in the class needs to be executed by the thread. * And at this point, in order to distinguish which code can be executed by the thread, Java provides a run () in the thread class to contain code that is executed by the thread. */ Public classMyThreadextendsThread {@Override Public voidrun () {//In general, code that is executed by threads must be time-consuming. So we use loops to improve for(intx = 0; x < 300; X + +) {System.out.println (x); } }} Public classMythreaddemo { Public Static voidMain (string[] args) {//Create two Thread objectsMyThread my1 =NewMyThread (); MyThread My2=NewMyThread (); My1.start (); My2.start (); }}
Steps:
1, custom class Myrunnable implementation Runnable interface
2. Rewrite the run () method
3. Creating objects of the Myrunnable class
4. Create the object of the thread class and pass the C-Step object as a construction parameter
Public classMyrunnableImplementsRunnable {@Override Public voidrun () { for(intx = 0; x < 100; X + +) { //The method of the thread class cannot be used directly because of the way the interface is implemented, but it can be used indirectlySystem.out.println (Thread.CurrentThread (). GetName () + ":" +x); } }}/** Mode 2: Implement Runnable interface * Step: * A: Custom class Myrunnable Implementation runnable interface * B: Override Run () method * C: Create object of Myrunnable class * D: Create the object of the thread class and pass the C-Step object as a construction parameter*/ Public classMyrunnabledemo { Public Static voidMain (string[] args) {//to create an object of the Myrunnable classMyrunnable my =Newmyrunnable (); //creates an object of the thread class and passes the C-step object as a construction parameter//Thread (Runnable target)Thread T1 =NewThread (my); Thread T2=NewThread (my); T1.setname ("Zhangsan"); T2.setname ("Lisi"); //Thread (Runnable target, String name)Thread T1 =NewThread (My, "Zhangsan"); Thread T2=NewThread (My, "Lisi"); T1.start (); T2.start (); }}
Benefits of implementing interface methods:
1. The limitations of Java single inheritance can be avoided.
2. Suitable for multiple same program code to deal with the same resource situation, the thread with the program code, data effectively separated, better embodies the object-oriented design ideas.
Get and set the thread name
Basic methods for getting and setting the thread class:
Public final String GetName () public final void SetName (string name)
In fact, by constructing the method can also give the name of the thread
How do I get the name of the thread where the main method resides?
public static Thread CurrentThread ()
This allows you to get the name of the thread where any method resides
The sample code is as follows:
Public classMyThreadextendsThread { PublicMyThread () {} PublicMyThread (String name) {Super(name); } @Override Public voidrun () { for(intx = 0; x < 100; X + +) {System.out.println (GetName ()+ ":" +x); } }} Public classMythreaddemo { Public Static voidMain (string[] args) {//To create a thread object//non-parametric construction +setxxx ()MyThread my1 =NewMyThread (); MyThread My2=NewMyThread (); //Call method Set nameMy1.setname ("Zhangsan"); My2.setname ("Lisi"); My1.start (); My2.start (); //to name a thread by constructing a method with a parameterMyThread my1 =NewMyThread ("Zhangsan"); MyThread My2=NewMyThread ("Lisi"); My1.start (); My2.start (); //What do I do if I want to get the name of the thread object where the main method is located? //Public static Thread CurrentThread (): Returns the currently executing thread objectSystem.out.println (Thread.CurrentThread (). GetName ()); }}
Thread scheduling
If our computer has only one CPU, then the CPU can only execute one instruction at a time, and the thread only gets the CPU time slice, that is, the right to use, to execute the instruction. So how does Java make calls to threads?
There are two scheduling models for threads:
- The time-sharing scheduling model uses CPU's use of the thread in turn, evenly allocating the CPU-
- Preemptive scheduling models prioritize high-priority threads to use the CPU, and if the threads have the same priority, they randomly select a higher-priority thread to get more CPU time slices.
Java uses a preemptive scheduling model.
Public final int getpriority () public final void setpriority (int newpriority)
The sample code is as follows:
Public classThreadPriorityextendsThread {@Override Public voidrun () { for(intx = 0; x < 100; X + +) {System.out.println (GetName ()+ ":" +x); } }}/** Public final int getpriority (): Returns the priority of the thread object * How do I prioritize thread objects? * Public final void setpriority (int newp riority): Change the priority of the thread. * * NOTE: * Thread default priority is 5. * The range of thread priority is: 1-10. * High Thread priority only indicates a high probability of the CPU time slices obtained by the thread, but only when the number of times is higher, or multiple runs, can you see a better effect. * * */ Public classThreadprioritydemo { Public Static voidMain (string[] args) {threadpriority TP1=Newthreadpriority (); ThreadPriority TP2=Newthreadpriority (); ThreadPriority TP3=Newthreadpriority (); Tp1.setname ("Zhangsan"); Tp2.setname ("Lisi"); Tp3.setname ("Wangwu"); //get the default priority levelSystem.out.println (Tp1.getpriority ()); System.out.println (Tp2.getpriority ()); System.out.println (Tp3.getpriority ()); //Set Thread Priority//tp1.setpriority (100000); //set the correct thread priorityTp1.setpriority (10); Tp2.setpriority (1); Tp1.start (); Tp2.start (); Tp3.start (); }}
Java Multithreading Series-Thread implementation and scheduling