privatefuntest2(){
lifecycleScope.launch{val startTime = System.currentTimeMillis()val a =getDataA()val b =getDataB()val sum = a + b
//D/MainActivity: test2: sum = 3,耗时:3008
Log.d(TAG,"test2: sum = $sum,耗时:${System.currentTimeMillis()- startTime}")}}privatesuspendfungetDataA(): Int {delay(1000)return1}privatesuspendfungetDataB(): Int {delay(2000)return2}
D/MainActivity: test2: sum = 3,耗时:3008
协程中多个耗时任务的并行
如果需要并行,例如请求多个接口拿到数据后才能进行操作
privatefuntest3(){
lifecycleScope.launch{val startTime = System.currentTimeMillis()val a = lifecycleScope.async{getDataA()}val b = lifecycleScope.async{getDataB()}val sum = a.await()+ b.await()//D/MainActivity: test3: sum = 3,耗时:2009
Log.d(TAG,"test3: sum = $sum,耗时:${System.currentTimeMillis()- startTime}")}}privatesuspendfungetDataA(): Int {delay(1000)return1}privatesuspendfungetDataB(): Int {delay(2000)return2}