Before we get to threads, we need to look at the mother of threads: the process. Process is a running activity of a program on a data set in a computer. It is the basic unit of resource allocation and scheduling in the system and the basis of operating system structure. In the early process-oriented computer architecture, the process is the basic execution entity of the program. In modern thread-oriented computer architectures, processes are containers for threads. A program is a description of data and its organizational form, and a process is an entity of the program. In a nutshell,.exe files on Windows, executables on Linux /MacOS, these are programs; When we execute these executable files, the instructions in the program will be loaded, and we get a process of the program. The following figure shows the processes currently running in MacOS.
- The NEW state indicates that the thread has just been created and has not yet started execution
- When a thread calls the start() method, it is in the RUNNABLE phase, indicating that it is ready to run
- Once the thread has acquired the resource, it starts executing the instructions in the run() method, which is in the RUNNING phase
- If a thread calls sleep(), wait(), suspend(), or suspend() during execution, or encounters an I/O block or synchronous lock block, it suspends execution, waits for the blocking time to end, and returns to the RUNNABLE state. A thread’s BLOCKED state does not resume running immediately after it finishes, but rather in a RUNNABLE state, waiting for resources to be acquired.)
- The threads TERMINATED are in an irreversible state of execution: NEW->RUNNABLE and RUNNABLE/RUNNING-> The resources are released in TERMINATED state. That is, threads cannot return from the RUNNABLE state to the NEW state or the TERMINATED state to the RUNNABLE/RUNNING state.