Kotlin cancel CoroutineScope.launch的任务后仍运行
import kotlinx.coroutines.*
fun main() {
runBlocking {
val coroutineScope = CoroutineScope(Dispatchers.IO)
val job = coroutineScope.launch {
var i = 0
while (i < Int.MAX_VALUE) {
i++
println(i)
}
}
// 2ms 取消协程
delay(2)
println("cancel...")
job.cancel()
coroutineScope.cancel()
println("cancel!")
}
}
...
997
998
999
cancel!
1000
1001
1002
...
加上 coroutineScope.isActive,控制while循环。
import kotlinx.coroutines.*
fun main() {
runBlocking {
val coroutineScope = CoroutineScope(Dispatchers.IO)
val job = coroutineScope.launch {
var i = 0
while (i < Int.MAX_VALUE && coroutineScope.isActive) {
i++
println(i)
}
}
// 2ms 取消协程
delay(2)
println("cancel...")
job.cancel()
coroutineScope.cancel()
println("cancel!")
}
}
...
598
599
600
cancel!Process finished with exit code 0
也可以加上:
yield()
控制:
import kotlinx.coroutines.*
fun main() {
runBlocking {
val coroutineScope = CoroutineScope(Dispatchers.IO)
val job = coroutineScope.launch {
var i = 0
while (i < Int.MAX_VALUE) {
yield()
i++
println(i)
}
}
// 2ms 取消协程
delay(2)
println("cancel...")
job.cancel()
coroutineScope.cancel()
println("cancel!")
}
}
...
108
109
110
cancel!

5695






