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/