美文网首页
Android kotlin 中 Dispatchers.Unc

Android kotlin 中 Dispatchers.Unc

作者: 雁过留声_泪落无痕 | 来源:发表于2023-07-13 21:13 被阅读0次

    结论

    当协程启动时,协程在启动它的线程上运行,遇到挂起函数并恢复时,它将在挂起函数指定的线程上运行。

    测试

    @Test
    @InternalCoroutinesApi
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
    
        val outer = ExperimentalCoroutineDispatcher(1, 1, "outer")
        runBlocking(outer) {
            val inner = ExperimentalCoroutineDispatcher(1, 1, "inner")
            val third = ExperimentalCoroutineDispatcher(1, 1, "third")
    
            println("--1--${Thread.currentThread().name}--") // outer
            CoroutineScope(Dispatchers.Unconfined).launch {
                println("--2--${Thread.currentThread().name}--") // outer
        
                withContext(inner) {
                    println("--3--${Thread.currentThread().name}--") // inner
                }
                println("--4--${Thread.currentThread().name}--") // inner
    
                withContext(third) {
                    println("--5--${Thread.currentThread().name}--") // third
                }
                println("--6--${Thread.currentThread().name}--") // third
            }
            println("--7--${Thread.currentThread().name}--") // outer
        }
    
        Thread.sleep(3000L)
        println("done")
    }
    

    日志:

    --1--outer-worker-1 @coroutine#1--
    --2--outer-worker-1 @coroutine#2--
    --7--outer-worker-1 @coroutine#1--
    --3--inner-worker-1 @coroutine#2--
    --4--inner-worker-1 @coroutine#2--
    --5--third-worker-1 @coroutine#2--
    --6--third-worker-1 @coroutine#2--
    done
    

    可以看到 1 在 outer 线程,导致 2 也在 outer 线程,3 不用说肯定在 inner 线程,withContext 这个挂起函数恢复后,4 就运行在了 withContext 指定的线程 inner;5 和 6 同理,都在 third 线程;7 自然是在 outer 线程。

    综上,如结论所述。

    相关文章

      网友评论

          本文标题:Android kotlin 中 Dispatchers.Unc

          本文链接:https://www.haomeiwen.com/subject/qpzmudtx.html