delay(3000) withContext(Dispatchers.IO) { println(" net "+ Thread.currentThread().name) (1..times).forEach { } } return "result for request $requestName" }
同步调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
fun main() = runBlocking { Dispatchers.Main var result3 = getMessageFromNet("async1" , 100000) var result4 = getMessageFromNet("async2" , 800000)
println("merge result ${result3.toString()} , ${result4.toString()}") } 运行结果: request: async1 start ----- net DefaultDispatcher-worker-1 request: async2 start ----- net DefaultDispatcher-worker-1 merge result result for request async1 , result for request async2
在第一个getMessageFromNet函数返回结果以后才发起第二次调用。
异步调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
fun main() = runBlocking { Dispatchers.Main
var result3 = async { getMessageFromNet("async1" , 100000) } var result4 = async { getMessageFromNet("async2" , 800000) }
val await = result3.await() val await1 = result4.await()
println("merge result ${await.toString()} , ${await1.toString()}") } 运行结果: request: async1 start ----- request: async2 start ----- net DefaultDispatcher-worker-1 net DefaultDispatcher-worker-2 merge result result for request async1 , result for request async2