await后不执行log5的问题

来源:12-6 案例:仿官方框架实现 async

黑金白兔

2023-07-24

suspend fun main() {
    log(1)
    val deferred = async {
        log(2)
        delay(1000)
        log(3)
        "Hello"
    }
    log(4)
    val result = deferred.await()
    log(5, result)
}

执行后的输入日志为:

22:37:31:926 [main] 1
22:37:32:010 [main] 4
22:37:32:012 [DefaultDispatcher-worker-0] 2
22:37:33:027 [DefaultDispatcher-worker-1] 3

没有执行log5。
deferred.await()的实现如下:

class DeferredCoroutine<T>(context: CoroutineContext) : AbstractCoroutine<T>(context), Deferred<T> {
    override suspend fun await(): T {
        return when(val currentState = state.get()) {
            is CoroutineState.InComplete -> awaitSuspend()
            is CoroutineState.Complete<*> -> (currentState.value as T?) ?: throw currentState.exception!!
        }
    }

    private suspend fun awaitSuspend(): T = suspendCoroutine<T> {
        continuation ->
        doOnCompleted { result ->
            continuation.resumeWith(result)
        }
    }
}

DefaultDispatcher的实现如下:

object DefaultDispatcher: Dispatcher {
    private val threadGroup = ThreadGroup("DefaultDispatcher")
    private val threadIndex = AtomicInteger(0)

    private val executor = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors()) {
        runnable ->
        Thread(threadGroup, runnable, "${threadGroup.name}-worker-${threadIndex.getAndIncrement()}")
            .apply { isDaemon = true }
    }

    override fun dispatch(block: () -> Unit) {
        executor.submit(block)
    }
}
写回答

1回答

bennyhuo

2023-07-25

同学发一下完整的可以运行的项目源码我帮你看看?我用 CoroutineLite 运行了一下你的 demo,是可以打印 5 的

//img.mukewang.com/szimg/64bf0c680932ab9109950286.jpg

0
0

学会Kotlin 突破开发语言瓶颈

如果有一门语言可以取代Java,那么它一定是Kotlin。

1777 学习 · 487 问题

查看课程