默认情况下。他们的顺序执行的
runBlocking {
val time1 = measureTimeMillis {
val one = doOne()
val two = doTwo()
Log.e(TAG, "the 1 result:${one + two}")
}
Log.e(TAG, "Completed 1 in $time1 ms")
}
如何改为并发执行呢?
binding.btClick6.setOnClickListener {
runBlocking {
val time2 = measureTimeMillis {
val one = async { doOne() }
val two = async { doTwo() }
Log.e(TAG, "the 2 result:${one.await() + two.await()}")
}
Log.e(TAG, "Completed 2 in $time2 ms")
}
}
使用async
但是千万不要使用这种写法
//错误示范
val time3 = measureTimeMillis {
val one = async { doOne() }.await()
val two = async { doTwo() }.await()
Log.e(TAG, "the 3 result:${one + two}")
}
Log.e(TAG, "Completed 3 in $time3 ms")
否则还会是2s