Android kotlin 中 Dispatchers.Unc

2023-07-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 线程。

综上,如结论所述。

上一篇下一篇

猜你喜欢

热点阅读