1, first clear point, for the single core CPU, at any one time only one thread is running. So what's the point of multithreading? For example, there is only one person to do several tasks. A single thread is that the task is done one at a time, and one task must be done before another is done. Multithreading is to do this task, one will do that task, each task to do a while, constantly switching. Obviously, the end of all tasks, multithreading must be more time-consuming than a single thread. Why? Because, multi-threaded to switch between different tasks, switching must be time-consuming. So the question is, since multithreading is more time-consuming than a single thread, why do you want multiple threads? There is a fatal problem with a single thread, that is, the whole process of running the threads, the other threads must wait, not respond to the user's commands, the user experience is too poor, as if the computer crashes. If single-threaded, you can imagine that the user can not write the document when listening to the song, this experience is too bad. Multi-threaded, single-core CPU will do this task, one will do that task, switching time is millisecond, the user can not feel completely. In order to give users the illusion, feel these tasks parallel operation.
2. Synchronous usage Scenario: Multiple threads access a piece of data at the same time, also called a shared area. For multiple threads accessing a piece of data at the same time, synchronization must be used, otherwise unsafe conditions may occur. such as dirty reads in the database. However, multiple threads accessing a piece of data at the same time, there is a situation that does not require synchronization technology, that is atomic operations, that is, the operating system at the bottom to ensure that the operation is either completed or not.
3. Asynchronous usage scenario: Only one thread accesses the current data. For example, the observer pattern, no shared area, subject changes, notifies the observer to update, the subject continues to do its own thing, does not need to wait for the observer to work after the update has been completed.
synchronous, asynchronous, multi-threaded