What is the Thread
Each instance of the Thread class (which calls the start() method and does not terminate) represents a Thread in the JVM,
Note that Runnable and Callable are not threads,
When Thread.start(), the JVM adds a worker/execution stream (threads) and a stack of methods.
The smallest unit of execution in Java is a method. Each thread has a method stack, which contains a method frame. After a method is executed, the frame is destroyed and the following frame is executed.
The lowest method frame executed by any method in Java must be the main or Thread.run() method of class XXX, and nothing else.
The root of the multithreading problem
Synchronous execution of different execution streams is the root of all threading problems.
At the code level, code is written from the top down, and conventional understanding programs should be executed from the top down.
However, when the program is running, it is true that two threads are ++ on I at the same time, which is somewhat counterintuitive, and this operation will cause conflicts, which may lead to errors.
Which thread will execute the code in the figure below?
The answer is not sure, because the diagram presents a task to a thread pool, and the implementation of the thread pool decides who executes the task.
Will the exception thrown in the figure be caught and printed by the main method?
The answer is no, because the main method can only catch exceptions thrown by the frame in the main thread, and the code indicated by the arrow in the following figure already belongs to the frame in another thread, which is counter-intuitive.
This is easier to understand because we are starting a new thread, and the frames between the threads are isolated and cannot be captured by the Main method.
We called sayHello twice, once on Thread and once on Main.
Use jStack to view thread information in the current process:
The sayHello method is used in a Thread war between main and thread0. The sayHello method is used in a Thread war between main and thread0. The sayHello method is used in a Thread war between main and thread0. Just start a new thread in the main thread and let it do something.
conclusion
The problem and complexity of multi-threading lies in counterintuition and uncertainty of execution. Their respective resources (internal local variables of stack frame, etc.) are independent from each other, but the shared resources will also produce competition, resulting in deadlock, calculation errors and a series of problems.
If the program has only one thread, the code is always serialized, there are no deadlocks and other problems, but because we want to make full use of the resources of the computer, help us do things faster, we need to use multithreading,
At the same time to do a good job in the use of multithreading encountered problems, followed by more ~