Analysis of Kotlin coroutines – what is a coroutine?
The use of Kotlin coroutines https://blog.csdn.net/qq_17798399/article/details/95245996
What is a coroutine?
First of all, the kotlin coroutine is an extension library of kotlin (kotlinx.coroutines).
Threads are generally used to do some complicated and time-consuming operations in Android development, so as to avoid ANR caused by time-consuming operations blocking the main thread. For example, IO operations need to be completed in new threads. However, if too many threads are used in a page, switching between threads consumes a lot of memory resources. We all know that threads are controlled and scheduled by the system, so it is difficult to control the use of threads. At this time, the kotlin coroutine shows its advantages. The kotlin coroutine runs on the thread, and its switching is controlled by the program itself, which greatly reduces both CPU consumption and memory consumption.
Difference and relationship between coroutine and thread:
Threads and coroutines have fundamentally different purposes:
- The purpose of the thread is to improve the utilization rate of CPU resources, so that multiple tasks can run in parallel, so the thread is to serve the machine.
- The purpose of the coroutine is to allow multiple Better collaboration between tasks is mainly reflected in the code logic, so the coroutine is to serve people, the people who write the code. (It is also possible that the result can improve the utilization of resources, but it is not the original purpose)
In terms of scheduling, coroutines are also different from threads:
- The scheduling of threads is completed by the system, generally preemptive, allocated according to priority, and is space division multiplexing.
- The scheduling of coroutines is specified by the developer according to the program logic Well, the reasonable allocation of resources to different tasks in different periods is time-division multiplexed.
The difference in function:
- The coroutine ensures that the code logic is sequential, regardless of whether the synchronous operation is an asynchronous operation, the previous one is completed, the latter one will start.
- Threads can be scheduled to execute on the CPU, so that the code can actually run.
Relationship between coroutines and threads:
Coroutines do not replace threads, but are abstracted from threads. Threads are divided CPU resources. Coroutines are organized code flows. Coroutines need threads to carry and run. Threads are coroutines. resources, but the coroutine does not directly use the thread, the coroutine directly uses the executor (Interceptor), the executor can be associated with any thread or thread pool, and can make the current thread, UI thread, or Create a new process. It can be summarized as follows:
- Threads are the resources of the coroutine.
- The coroutine uses the resource of the thread indirectly through the Interceptor.
Kotlin Chinese Station