Basic concept Programs & threads & Processes
- A program is a piece of code that can provide business functionality, and it can contain 1 or more processes. The program runs on the OS as a process to various resources (CPU, Memory, Disk). ) is consumed and processed.
- A process is the smallest unit of the OS's resource scheduling: The process consumes the CPU independently at any time, only one process can occupy the CPU, the other processes are waiting, the process also has independent memory, and when it collapses, it does not affect other processes in the OS, but the cost of switching between processes is higher , the frequent switching process of the OS can cause heavy pressure on CPU and memory.
- A thread is the smallest unit of a CPU call, and does not have a stack of other system resources (except for some storage variables). ); The memory of the same process is shared between different threads, and access to the same memory variable is achieved through a lock mechanism, and once a thread dies, the entire process is killed because of a memory lock.
Take the factory simulation OS operating principle as an example to illustrate
The OS corresponds to the factory, which has many workshops (processes), each with separate equipment (memory) and multiple workers (threads). The workshop was started by power supply equipment, but a power supply unit had only one connector (CPU), and the different workshops were polled for start-up, but a workshop started when multiple workers could work in parallel. Workers in the same workshop may use the same equipment when working in parallel, need to queue (lock mechanism) when using the same device, and a device can be released to be used by the next worker.
What is the case with multithreading?
Concurrent operations that do and share certain variables at the same time can be used only by threads and not by processes. For example, asynchronous calls must be multi-threaded, performance testing simulation of multiple users at the same time the request must also be multi-threaded (otherwise only one user after the request of another user to send), high performance requirements and can be split the task is recommended to use multi-threading, but must pay attention to maintain the robustness of the code.
Java Fundamentals: Multithreading