协程并不是一个新的概念,它并不是 Kotlin 发明的。它们已经存在了几十年,并且在 Go 等其他一些编程语言中很受欢迎。 协程(英语:coroutine)是计算机程序的一类组件,推广了协作式多任务的子程序,允许执行被挂起与被恢复。相对子例程而言,协程更为一般和灵活,但在实践中使用没有子例程那样广泛。协程更适合于用来实现...
You will see how you can convert existing code, which relies on callbacks, to suspendable functions, which are called in the same way as regular, blocking, functions. Throughout it all, you will learn what the most important piece of the coroutines puzzle is....
Kotlin 协程本质上是依托线程执行的。具体地说,当一个 Kotlin 协程被创建,底层会创建相应的 Task (Runnable 实例),然后将 Task 添加到任务队列(LockFreeTaskQueue),并发放一个许可证,唤醒一个 Worker。Kotlin 后台维护了共享线程池 CoroutineScheduler,里面有若干个 Worker 守护线程 (Thread 实例),Worker 会从任务...
you would have two functions with the same parameters, but you’d have to wrap the suspendable function in alaunchblock. This is how the Kotlin coroutines APIs are built, but the actual function call doesn’t change.