gpt4 book ai didi

android - Kotlin 协程 : one single coroutine at a time in single thread

转载 作者:行者123 更新时间:2023-12-02 12:42:27 27 4
gpt4 key购买 nike

考虑下面这段代码,我正在尝试使用 Executors.newFixedThreadPool(1).asCoroutineDispatcher()创建单线程调度程序;我想要 launch(singleThread){...} 内的代码顺序执行

预期结果应如下所示,因为 async-block#2 首先到达/获取单线程

async block #2
async block #1
single thread block #2
single thread block #1
The answer is 3


但实际结果是

async block #2
async block #1
single thread block #1
single thread block #2
The answer is 3


single-thread-block-#2 和 single-thread-block-#1 似乎并行运行,singleThread 在这里没有什么不同

import java.util.concurrent.Executors
import kotlinx.coroutines.*
import kotlin.system.*

val singleThread = Executors.newFixedThreadPool(1).asCoroutineDispatcher()

fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
val one = async { // async block #1
delay(200)
println("async block #1")
launch (singleThread) {
delay(500)
println("single thread block #1")
}
2
}
val two = async { // async block #2
delay(100)
println("async block #2")
launch (singleThread) {
delay(1500)
println("single thread block #2")
}
1
}
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
}

最佳答案

注意delay()suspend代码中的函数。它是通过协程挂起实现的。这意味着当你调用delay时,代码的执行被暂停。并且仅在超时后恢复。线程(例如,您通过 async(singleThread) {..} 使用的线程不忙于等待时间过去。

整体场景是这样的

  • ...
  • 打印的“异步 block #2”
  • 任务 2 正在 singleThread 上运行
  • 任务 2 被 delay(1500) 挂起, singleThread是免费的
  • 任务 1 在 singleThread 上启动
  • 任务 1 被 delay(500) 挂起, singleThread是免费的
  • 那时我们有延迟队列:
  • 恢复delay(500)任务 1
  • 恢复delay(1500)任务 2
  • 一段时间后
  • resume(500)安排任务 1 的第二部分在 singleThread 中运行
  • 一段时间后
  • resume(1500)安排任务 2 的第二部分在 singleThread 中运行
  • 关于android - Kotlin 协程 : one single coroutine at a time in single thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942872/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com