14-挂起函数
12.4 挂起函数
使用关键字suspend修饰的函数称为挂起函数,挂起函数只能从协程代码内部调用,普通的非协程代码则不能调用。协程函数的格式如下。
suspend fun 函数名(参数名: 参数类型):返回值类型{
函数体
}
挂起函数只允许由协程或者另一个挂起函数调用,下面是协程调用挂起函数的例子。
suspend fun hangUpDemo() {
run(CommonPool) {
delay(1000L)
println("run suspend")
}
println("hangUpDemo")
Thread.sleep(2000L)
}
fun callSuspendFun() {
launch(CommonPool) {
hangUpDemo()
}
}
事实上,要启动协程,必须有一个挂起函数,它通常是匿名的Lambda表达式。