kotlin 协程之作用域
2022-01-12 本文已影响0人
咸死的鱼_O
coroutineScope 与 runBlocking
- runBlocking 是常规函数,而coroutineScope 是挂起函数
2.它们都会等待期协程体以及所有子协程结束,主要区别在于runBlocking 方法会阻塞当前线程来等待,而coroutineScope 只是挂起,会释放底层线程用于其他用途
coroutineScope 与supervisorScope
1.coroutineScope :一个协程失败了,所有其他兄弟协程也会被取消
2.supervisorScope:一个协程失败了,不会影响其他协程
coroutineScope :
val b = runBlocking {
coroutineScope {
val job1 = async {
delay(1000)
println("job1 finished")
}
val job2 = async {
delay(500)
println("job2 finished")
}
}
执行输出内容:
7905-7905 I/System.out: job2 finished
7905-7905 I/System.out: job1 finished
如果在执行过程中job2 出现异常协程被取消,那么job1的执行将会被取消
val b = runBlocking {
coroutineScope {
val job1 = async {
delay(1000)
println("job1 finished")
}
val job2 = async {
delay(500)
println("job2 finished")
throw IllegalArgumentException()
}
}
执行结果:
8670-8670 I/System.out: job2 finished
supervisorScope:
val b = runBlocking {
supervisorScope {
val job1 = async {
delay(1000)
println("job1 finished")
}
val job2 = async {
delay(500)
println("job2 finished")
throw IllegalArgumentException()
}
}
输出结果:
10776-10776 I/System.out: job2 finished
10776-10776 I/System.out: job1 finished