我正在学习Kotlin的协程,我是https://try.kotlinlang.org/中在线运行代码的初学者
我尝试在网站上测试代码A,但是像图像A一样出现很多错误,我该如何解决?
代码A
import kotlinx.coroutines.*
fun main(args: Array<String>) {
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
图片
最佳答案
尝试运行以下代码:
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun main() = runBlocking<Unit> { //here i made change
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
输出将是:)
Cancelling child
Child is cancelled
Parent is not cancelled
关于kotlin - 测试代码时为什么会出现错误 “Unresolved reference: launch”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60732166/