//1.协程取消执行 fun mainCancel() = runBlocking { var job = launch { repeat(20) { i -> println("$i") delay(1000) } } delay(1100) println("delay ...") cancelAndJoin(job) println("end") } private suspend fun cancelAndJoin(job: Job) {//重构 job.cancel() //取消执行协程 job.join() //等待协程 } //2.要协程操作完成后,协程才可以取消 fun main_cancel() = runBlocking { val startTime = System.currentTimeMillis() //获取系统时间 val job = launch(Dispatchers.Default) { var nextTime = startTime var i = 0 while (i < 5) { if (System.currentTimeMillis() >= nextTime) {//防并发 println("${i++}") nextTime += 1000 } } } delay(1000) println("main:") job.cancelAndJoin()//先进入循环操作,后执行取消协程(协程不是立即执行的,因为循环还在运行中) println("end:") } //3.想在操作中,取消协程 在操作中加判断 fun main_isActive() = runBlocking { val startTime = System.currentTimeMillis() //获取系统时间 val job = launch(Dispatchers.Default) { var nextTime = startTime var i = 0 while (isActive) {//判断是否活跃 if (System.currentTimeMillis() >= nextTime) {//防并发 println("${i++}") nextTime += 1000 } } } delay(1000) println("main:") job.cancelAndJoin()//先进入循环操作,后执行取消协程(协程不是立即执行的,因为循环还在运行中) println("end:") } //4.关闭资源 finally 。withContext(NonCancellable)里面取消不了 fun main_finally() = runBlocking { val job = launch() { try { repeat(10000) { i -> println("$i") delay(1000) } } finally {//关闭资源 println("finally...") withContext(NonCancellable) { delay(1000L) println("delay...end")//取消不了 在withContext(NonCancellable)代码块里 } } } delay(1000) println("main:") job.cancelAndJoin()//先进入循环操作,后执行取消协程(协程不是立即执行的,因为循环还在运行中) println("end:") } //5.操作超时 fun main_withTimeoutOrNull() = runBlocking { val job = withTimeoutOrNull(1200) {//用withTimeout会报异常 repeat(1000) { i -> println("$i") delay(1000) } } delay(1000) println("end:") }
kotlin 取消和超时
最新推荐文章于 2024-03-12 20:36:47 发布