gpt4 book ai didi

kotlin - 为什么 “repeat”函数在kotlin中可以取消

转载 作者:行者123 更新时间:2023-12-02 13:09:20 30 4
gpt4 key购买 nike

fun main(args: Array<String>) = runBlocking<Unit> {
val job = launch {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
job.join() // waits for job's completion
println("main: Now I can quit.")

}
此代码不检查isActive或使用暂停功能,但可以取消

最佳答案

这是与Java线程的类比:

1)明确检查中断标志:

while (!Thread.interrupted()) {
// loop code
}

2)调用可中断操作:
while (true) {
Thread.sleep(1);
// loop code
}

在这两种情况下,线程都将响应提升的中断标志。

在协程中, delay()Thread.sleep()的副本,而 isActive标志是 Thread.interrupted标志的副本。

因此,当你写
delay(1)

协程将在线程外进行调度,当它的恢复时间到来时,在 continuation.resume()调用内部将首先检查 isActive标志。如果提出,它将抛出 CancellationException

关于kotlin - 为什么 “repeat”函数在kotlin中可以取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50676327/

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