kotlin 中的协程
runBlocking 和 coroutineScope 的区别
他们是不同的概念
runBlocking 会阻塞当前线程 直到runBlocking 域中执行完成
fun main(arr:Array<String>) {
runBlocking(Dispatchers.Default){
delay(1000)
println("runBlocking ${Thread.currentThread()}")
}
println("main ${Thread.currentThread()}")
}
coroutineScope 不会阻塞当前线程 只是一个suspend function 要放到 launch 函数中执行
fun main(arr:Array<String>) {
GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
coroutineScope{
println("coroutineScope ${Thread.currentThread()}")
}
}
println("main ${Thread.currentThread()}")
}
协程要放到指定的Scope 中 本质上还是线程池
withContext 的作用在指定的Scope中可以切回当前线程 能够把本是异步的可以写成类似同步的写法
fun main(arr:Array<String>) {
GlobalScope.launch(UI){
println("launch ${Thread.currentThread()}")
val str = withContext(IO){
Thread.sleep(1000)
println("withContext ${Thread.currentThread()}")
return@withContext "abcdef"
}
}
println("main ${Thread.currentThread()}")
Thread.sleep(2000)
}
模拟一个网络请求
suspend fun test():String{
return withContext(IO){
delay(1000)
println("处理耗时任务 ${Thread.currentThread()}")
"获取网络数据"
}
}
fun main(arr:Array<String>) {
GlobalScope.launch(UI) {
val data = test()
println("$data ${Thread.currentThread()}")
}
Thread.sleep(3000)
println("main ${Thread.currentThread()}")
}