Java multithreading Overview
/* Multithreading
1. First, the process is the program in progress.
Each process has an execution program. This order is an execution path or a control unit.
2. Thread: it is an independent process unit in the process.
The thread is controlling the execution of the process.
At least one process in a process
Java VM (Virtual Machine) starts a process java.exe
At least one thread in this process is responsible for java program execution.
The code run by this thread exists in the main method.
This thread is called the main thread.
Expansion: in fact, more details about JVM and jvm start more than one thread, as well as the thread responsible for the garbage collection mechanism.
3. How can I customize a thread in custom code?
By searching APIs, java has provided descriptions of such things as threads.
The first way to create a Thread is to inherit the Thread class.
Procedure:
1. The definition class inherits the Thread.
2. Rewrite the run method in the Thread class.
Objective: To store custom code in the run method for threads to run
3. Call the start method of the thread.
This method has two functions: 1. Start the thread 2. Call the run Method
*/
/*
Knowledge
1. the CPU is switched without interruption. The actual switch is the thread in the process.
2. The speed is very fast and it cannot be felt quickly.
3. It is found that the running results are different each time. Because every thread is obtaining the execution right of the cpu, Whoever executes the cpu will run.
4. Clearly, at a certain time point, only one program can be executed (except for multiple cores)
5. the cpu is performing a quick switch, and it seems to be running at the same time.
6. We can use the image to describe the multi-thread operation to compete for the execution right of the cpu, reflecting the characteristics of multithreading: randomness (the cpu determines who gets the execution and how long the execution takes)
*/
/* Why overwrite the run method?
Thread is used to describe the Thread
This class defines a function for storing the code to be run by the thread. This storage function is the run method.
That is to say, the run method in the Thread class is used to store the code to be run by the Thread.
*/
Class Demo extends Thread
{
Public void run ()
{
For (int I = 0; I <60; I ++)
{
System. out. println ("Demo run" + I );
}
}
}
Class ThreadDemo
{
Public static void main (String args [])/* main thread */
{
Demo d = new Demo ();/* create an object, that is, create a thread * // * when the main thread reaches this path, a new control unit is created */
D. start ();/* Open the thread and execute the run method of the thread. D. run () is only because the object calls the method, but the thread is created and does not run */
For (int I = 0; I <60; I ++)
{
System. out. println ("aaa" + I );
}
}
}