我想找出Kotlin协程的执行顺序和线程切换。我使用withContext
来切换到另一个上下文并运行耗时的任务,因此不会阻塞主线程。但是科特林没有按预期切换上下文。
代码在kotlin游乐场上运行:https://pl.kotl.in/V0lbCU25K
无效的情况
suspend fun main() = runBlocking {
println("Hello,world!!!")
println(Thread.currentThread().name)
withContext(Dispatchers.IO) {
println("Before heavy load: ${Thread.currentThread().name}")
Thread.sleep(5000)
println("After heavy load: ${Thread.currentThread().name}")
}
println("waiting")
println(Thread.currentThread().name)
}
输出
Hello,world!!!
main @coroutine#1
Before heavy load: DefaultDispatcher-worker-1 @coroutine#1
After heavy load: DefaultDispatcher-worker-1 @coroutine#1
waiting
main @coroutine#1
以上代码块中的sleep
函数在与主线程相同的线程上运行并将其阻塞。
以下情况符合我的预期(耗时的任务不会阻塞主线程)
案例1
suspend fun main() = runBlocking {
println("Hello,world!!!")
println(Thread.currentThread().name)
launch {
println("Before heavy load: ${Thread.currentThread().name}")
Thread.sleep(5000)
println("After heavy load: ${Thread.currentThread().name}")
}
println("waiting")
println(Thread.currentThread().name)
}
输出
Hello,world!!!
main @coroutine#1
waiting
main @coroutine#1
Before heavy load: main @coroutine#2
After heavy load: main @coroutine#2
案例2
suspend fun main() = runBlocking {
println("Hello,world!!!")
println(Thread.currentThread().name)
launch {
withContext(Dispatchers.IO) {
println("Before heavy load: ${Thread.currentThread().name}")
Thread.sleep(5000)
println("After heavy load: ${Thread.currentThread().name}")
}
}
println("waiting")
println(Thread.currentThread().name)
}
输出
Hello,world!!!
main @coroutine#1
waiting
main @coroutine#1
Before heavy load: DefaultDispatcher-worker-1 @coroutine#2
After heavy load: DefaultDispatcher-worker-1 @coroutine#2