最近开始使用Kotlin协程
语法如下:
main(){
launch(Dispatchers.Main){
delay(2000)
print("inside coroutine")
}
print("outside coroutine")
}我知道首先打印外部协程,然后再打印内部协程,因为延迟是一个挂起函数,它只阻塞协程,而不是线程本身。
但是,由于协程需要在其他地方(例如在不同的线程上)执行才能知道何时恢复,这是如何处理的?
它可以是任何进程的密集挂起功能,而不是延迟。
我唯一不能理解的是,不管启动{}构建器中提供的调度程序是什么,挂起函数是否真的在幕后的另一个线程上运行?
发布于 2020-07-24 13:24:21
suspend函数被设计为阻塞当前的协程,而不是线程,这意味着它们应该在后台线程中运行。例如,delay函数在不阻塞线程的情况下,在给定时间内阻塞协程,并在指定时间后恢复线程。您可以创建一个在后台线程上运行的suspend函数,如下所示:
suspend fun someSuspendFun() = withContext(Dispatchers.IO) {
// do some long running operation
}使用withContext(Dispatchers.IO),我们将函数执行的上下文切换到后台线程。withContext函数也可以返回一些结果。
要调用该函数,我们可以使用协程构建器:
someScope.launch(Dispatchers.Main){
someSuspendFun() // suspends current coroutine without blocking the Main Thread
print("inside coroutine") // this line will be executed in the Main Thread after `someSuspendFun()` function finish execution.
}发布于 2020-07-24 10:52:09
delay()函数在幕后异步运行。如果使用Dispatchers.Main运行,其他挂起函数将阻塞线程
https://stackoverflow.com/questions/63065915
复制相似问题