小编zwl*_*lxt的帖子

为什么“withContext”不在“runBlocking”下切换协程?

我想了解kotlin协程的执行顺序和线程切换。我曾经withContext切换到另一个上下文并运行耗时的任务,因此主线程不会被阻塞。但 kotlin 并没有按预期切换上下文。

代码在 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)
}
Run Code Online (Sandbox Code Playgroud)

输出

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
Run Code Online (Sandbox Code Playgroud)

上面代码块中的函数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) …
Run Code Online (Sandbox Code Playgroud)

multithreading kotlin kotlin-coroutines

8
推荐指数
2
解决办法
5050
查看次数

标签 统计

kotlin ×1

kotlin-coroutines ×1

multithreading ×1