gpt4 book ai didi

kotlin - Kotlin TickerMode 之间的区别

转载 作者:行者123 更新时间:2023-12-02 13:37:11 25 4
gpt4 key购买 nike

我无法理解 Kotlin 股票 channel TickerMode.FIXED_DELAY and TickerMode.FIXED_PERIOD 之间的区别.我都玩过,但我无法从他们的行为中得出推论。我还阅读了 docs 中的示例.如果有更清晰的解释,我将不胜感激,并附有说明。

最佳答案

您可以在 coroutines sources 中找到区别在于 FIXED_PERIOD更复杂,并考虑到接收器无法在下一次调用 send 之前跟上和调整延迟的事实。 .但是,这可能很难证明,因为您需要测量接收器等待下一个滴答声所花费的时间。

附言请注意,此功能被标记为已过时,即“相应声明的设计存在严重的已知缺陷, future 将重新设计。”在这种情况下,原因是它没有与结构化并发集成。

fun main() = runBlocking {
println("\nFIXED_PERIOD")
val tickerPeriodMode = ticker(100, 0, mode = TickerMode.FIXED_PERIOD)
consumer(tickerPeriodMode)

println("\nFIXED_DELAY")
val tickerDelayMode = ticker(100, 0, mode = TickerMode.FIXED_DELAY)
consumer(tickerDelayMode)
}

private suspend fun CoroutineScope.consumer(ticker: ReceiveChannel<Unit>) {
val job = launch {
var i = 0
while (isActive) {
val waitTime = measureTimeMillis {
ticker.receive()
}
print("[%4d ms]".format(waitTime))

if (i++ == 1) {
delay(150)
println(" adding extra 150ms delay")
} else
println(" going ahead")
}
}
delay(1_000L)
job.cancel()
ticker.cancel() // indicate that no more elements are needed
}

输出
FIXED_PERIOD
[ 1 ms] going ahead
[ 91 ms] adding extra 150ms delay
[ 0 ms] going ahead
[ 46 ms] going ahead
[ 100 ms] going ahead
[ 102 ms] going ahead
[ 98 ms] going ahead
[ 100 ms] going ahead
[ 99 ms] going ahead
[ 100 ms] going ahead
[ 100 ms] going ahead

FIXED_DELAY
[ 0 ms] going ahead
[ 105 ms] adding extra 150ms delay
[ 0 ms] going ahead
[ 101 ms] going ahead
[ 100 ms] going ahead
[ 103 ms] going ahead
[ 103 ms] going ahead
[ 101 ms] going ahead
[ 101 ms] going ahead
[ 105 ms] going ahead

关于kotlin - Kotlin TickerMode 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53844266/

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