Kotlin协程
简介:
优点:写法很简单,轻量级,挂起几乎不消耗内存,速度上优于java的线程,性能损耗小,能大幅度提高并发性能,本人推荐使用协程,而不用传统的线程
代码
引入
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.18"
创建一个协程
launch(CommonPool) {
//这里需要运行的代码
}
协程里面嵌套协程
launch(CommonPool) {
//创建带返回值的协程async
var job = async(CommonPool) {
delay(5000L)
return@async "nihao"
}
var job1 = launch(CommonPool) {
delay(5000L)
return@async "nihao2"
}
}
协程的取消:
job1.cancel()
有关协程的挂起,恢复,调度这里就不做过多的介绍!!