1、runBlocking
会阻塞主线程,等待协程执行完,才会继续执行主线程
2、launch:Job
不会阻塞主线程,返回Job类型的对象
var job = GlobalScope.launch {
repeat(10) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
3、async
用于启动一个异步协程任务,与launch用法基本一样,不阻塞线程,区别在于:async的返回值是Deferred,将最后一个封装成了该对象。async可以支持并发,此时一般都跟await一起使用。
GlobalScope.launch {
val res1 = GlobalScope.async {
getRes1()
}
val res2 = GlobalScope.async {
getRes2()
}
val res = res1.await() + res2.await()
Log.i(TAG, "onCreate: $res")
}
private suspend fun getRes1(): Int {
delay(1000)
return 1;
}
private suspend fun getRes2(): Int {
delay(2000)
return 100;
}