fun main() = runBlocking { getUserInfo() getFriendList()}suspend fun getUserInfo() { println("getUserInfo: start time: ${System.currentTimeMillis()}") delay(2000L) println("getUserInfo: end time: ${System.currentTimeMillis()}") logX("suspend function1")}suspend fun getFriendList() { println("getFriendList: start time: ${System.currentTimeMillis()}") delay(2000L) println("getFriendList end time: ${System.currentTimeMillis()}") logX("suspend function2")}
Launch
fun main() = runBlocking { launch { println("launch1: start time: ${System.currentTimeMillis()}") delay(2000L) println("launch1: end time: ${System.currentTimeMillis()}") logX("launch1") } launch { println("launch2: start time: ${System.currentTimeMillis()}") delay(2000L) println("launch2: end time: ${System.currentTimeMillis()}") logX("launch2") } Unit}答案发表时间:
suspend函数必要4秒,launch必要2秒。我们来看看挂起函数和launch的实验模子:
suspend函数和launch这类的协程构建器是有本质上的差别的,suspend函数在Kotlin编译器的作用下会变成一个主动机,而launch这类都不是suspend,他们实在是将任务【分发】到线程池(在JVM平台上)上实现的实验。
suspend和协程构建器的连合之处就在await上:
public suspend fun await(): Tawait是一个挂起函数,后续的流程会像上图以上被挂起,我们来看这个例子:
fun main() = runBlocking { val def = async { println("async starts") delay(2000L) println("async end") "hello world" } println("message from main") println(def.await()) println("end of story")}/** message from main async starts async end hello world // end of story的输出被挂起到await实验完成再规复 end of story**/suspend函数到主动机的转换在末了一节会阐明。Kotlin Coroutine狭义的协程指的是通过构建器启动的协程,后文不再阐明。