Multithreading
1.Introduction of multithreading
If there is only one way to execute the program, the program is a single threaded program.
If there are multiple ways to execute, then changing the program is multithreading.
2.Process overview and multi process significance
If you want to know the thread, you must understand the process first, because the thread is dependent on the process.
(1).What is a process?
It’s the running application. It is an independent unit for resource allocation and scheduling. Each process has its own memory space and system resources.
(2).What is the meaning of multiple processes?
We see multiple applications running on a single computer, but we can see multiple applications running, that is, multiple processes.
Such as: listening to music (music process), playing games (game process). That is to say, you can execute multiple processes in one time period. And improve the utilization rate of CPU.
(3).A detail question?
Do you play games and listen to music at the same time?
The concept at the same time: representing points at the same time, such as seconds, milliseconds.
Answer: No, it’s impossible, because a single CUP can only handle one thing at a time, while playing games and listening to music, CUP is doing CUP between programs.
Switching at high speed makes us feel uninterrupted.
3.thread
(1).What is thread?
Multiple tasks can be performed within the same process. For every task, we can think of it as a thread.
Threading: the execution unit of a program, also called execution, is the most basic unit for CPU.
(2).Single thread and multithreading definition
Single thread: if the program has only one execution, then it is called single thread.
Multithreading: if the program has multiple execution paths, then it is called multithreading.
(3).The significance of multithreading
Multithreading exists not to speed up the execution of programs, but to improve the utilization of applications.
Program execution is to grab the right to use the CPU, and multiple processes are grabbing the right to use this time, if this process execution more energy, there will be a higher probability of grabbing
CPUThe executive power. Despite this, we still can’t guarantee which thread can grab CPU usage at any time, so thread execution is random.
(4).Differences between concurrency and parallelism
Concurrency: Represents the physical simultaneous occurrence of multiple programs running at the same time point in value.
Parallelism: Represents the logical simultaneous occurrence of multiple programs running at the same time.
4.JavaThe operation principle of the program and the startup of JVM.
(1).javaOperation principle of program
JavaThe command starts the Java virtual machine and starts the jvm, which is equivalent to launching an application or a process. Then the process will start a ‘main thread’ and then.
‘The main thread then calls the mian () method of the class, so the main () method runs in the main thread. All of the programs before that are single threaded.
(2).jvmIs the startup of multithreading?
Yes, the reason is that there is at least one main thread and there needs to be a garbage collection thread, because the garbage collection thread starts at the beginning and monitors in real time whether or not
There’s garbage, and when there’s not enough memory, the garbage collection thread is called to collect the garbage, which is why Java programs rarely crash.
5.How to achieve multithreading and multithreading implementation 1
(1).How to achieve multithreading?
Since threads are dependent on processes, we should create a process first, and since the process is created by the system, we should remove the function of the system to create a process.
The process comes out.
But the Java language can not directly call the system functions, so we can not directly implement the multi-threaded program, but Java can call c/c++ written programs to achieve
Multithreading, let C / C + + call the system program to create a process, then java to call such things, and let java to call such things and provide some classes for us to use
In this way, we can use java to achieve multithreading.
(2).javaWhat are the classes provided?
Through API, we know there are two ways to achieve this.
Implementation method 1: inheriting Thread class
Implementation steps:
A.Custom class, inheriting Thread class
B.Rewriting run () method in custom class
Why is the run () method?
C.Create custom class objects.
D.Start the thread.
Question 1: why do we rewrite the run () method instead of other methods?
Depending on the inheritance feature, we can use multithreading after inheriting the Tread class, but not all of the code in the method I defined needs it
To be multithreaded, that is, we just need to put the part of our code that needs to be multithreaded into the re-run () method
At the same time, we can also have code that we do not execute by multiple threads.
Question 2: which code is suitable for placement in the run () method?
Generally, the code that needs to be executed by the thread is tedious, that is to say, there will be two robbing the same thing again, in order to ensure that A in use.
It also allows B to be used.
Question 3: why do we call the run () method in Thread why it is still single threaded?
Code:
MyThread mt =new MyThread();
mt.start();
mt.start();
The code is abnormal because the same thread MT is called twice and thrown an exception: Illegal TreadStateException: Illegal thread state exception
MyThread mt =new MyThread();
MyThread mt2 =new MyThread();
mt.start();
mt2.start();
That’s the right thing to do.
If we call the run () method this way, it’s not exactly the same as if we call the normal method, all you see is
Single thread effect. To see the effect of multithreading, we need to call the start () method of Thread.
start()The two operations of the method are:
A:Make the thread execute.
B:java The run () method that the virtual machine calls the thread.
—>Interview questions:
ThreadWhat is the difference between run () and start ()?
run()Just encapsulating code executed by threads, there is no difference between direct invocation and general methods.
start():First, you start the thread, then use JVM to invoke the code in the run () method of the thread.
Matters needing attention:
The super run () is called in the re-run () method; that is, the method in the parent class is called, but this operation is not interesting.
We can delete it directly when we use it. Write the code that we need to execute in multithreading.
(3).A simple code implementation for multithreading:
public class MyThread extends Thread{
@Override
public void run() {
//super.run();
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
//test
public static void main(String[] args) {
MyThread mt =new MyThread();
MyThread mt1 =new MyThread();
mt.start();
mt1.start();
}
}
//Effect (two threads overlap when using CPU, indicating a multithreaded program).
517
518
0
1
6.Gets and sets the thread object name
(1).public final String getName();Gets the name of the thread.
public final String setName(String name);Set the ready-made name.
(2).Why does the output thread name default to Thread-0/Thread-1?
threadNo reference structure source:
class Thread{
public Thread(){
init(null,nill,”Threa-“+nextThreadNum(),0);
}
}
nextThreadNum()Method:
private static int threadinitNumber;//The default value is 0.
private static sychronized int nextThreadNum(){
return threadinitNumber++;//After + +, return to 0 first.
}
(3).How to get the name of the thread object of the main () method (for object names that are not Tread subclasses. )
public static Thread CurrentTraed():Gets the name of the thread object that is currently executing.
(4).Code implementation:
public class MyThread extends Thread{
//Method 2 when you test, you need to provide the class parameter structure and pass it to the parent class.
public MyThread(String name) {
// TODO Auto-generated constructor stub
super(name);
}
@Override
public void run() {
//super.run();
for (int i = 0; i < 1000; i++) {
System.out.println(getName()+”—“+i);
}
}
//test
public static void main(String[] args) {
//Method 1
/*MyThread mt =new MyThread();
MyThread mt1 =new MyThread();
mt.setName(“* “big pig”);
mt1.setName(“The piglet “); * /
//Method 2
/*MyThread mt =new MyThread(“* “big pig”);
MyThread mt1 =new MyThread(“The piglet “);
mt.start();
mt1.start();*/
//Thread that gets the main method
System.out.println(Thread.currentThread().getName());
}
}