kotlin 协程之作用域

coroutineScope 与 runBlocking

  1. 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容