A thread is an execution unit that executes a program's code during execution. In the Java language, threads have four states: Run, ready, suspend, end.
A process refers to a program that is being executed. threads, sometimes referred to as lightweight processes, are the smallest unit of program execution, a process that can have multiple threads, share the program's memory Space (code snippets, data segments, and heap space), and some process-level resources (such as open files) between threads, but each thread has its own stack space. The relationship between the process and the thread is as follows:
At the operating system level, the execution of the program is process-based, and each process typically has multiple threads executing concurrently, so why use multithreading? In fact, the use of multithreading for the development of the program has brought great convenience, specifically, there are several aspects of the content:
1) Use multithreading to reduce the response time of the program. In the case of single-threaded (single-threaded) cases where there is only a sequence of valid operations in the execution of a program, with a clear execution sequence between the different operations, if an operation is time consuming or is stuck in a long wait (such as waiting for a network response), the program will not respond to actions such as a mouse and keyboard, This time-consuming thread can be assigned to a separate thread to execute, making the program more interactive.
2) thread creation and switching overhead are less expensive than processes. Since starting a new thread must assign a separate address space to the thread, establish a number of data structures to maintain the thread code snippets, data segments, and so on, threads that run in the same process share code snippets, data segments, and threads are much less expensive to start or switch than processes. Multithreading is highly efficient in data sharing.
3) Multi-CPU or multi-core computer itself has the ability to perform multithreading, if using a single thread, will not be able to reuse computer resources, resulting in a huge waste of resources. Therefore, using multithreading on a multi-CPU computer can improve CPU utilization.
4) The use of multithreading can simplify the structure of the program, making the program easy to understand and maintain. A very complex process can be executed by dividing it into multiple threads.
From: "Java programmer interview written book" Official website
What is a thread? What is the difference between it and the process? Why use multithreading?