Kotlin协程 - - -上下文与异常处理

一.协程上下文

1.协程的上下文的组成

CoroutineContext是一组用于定义协程行为的元素。它由如下几项构成。
Job:控制协程的生命周期
CoroutineDispatcher:向合适的线程分发任务
CoroutineName:协程的名称,调试的时候很有用
CoroutineExceptionHandler:处理未被捕捉的异常

2.组合上下文中的元素

 @Test
 fun testCoroutineContext() = runBlocking {
               //这里把调度器和CoroutineName操作符相加
        launch(Dispatchers.Default + CoroutineName("test")) {
            println("I'm working in thread ${Thread.currentThread().name}")
        }
    }

打印结果:

I'm working in thread DefaultDispatcher-worker-1 @test#2

吃打印结果后面的名字@test#2 需要在test文件夹,进性单元测试才会出现。

3.协程上下文的继承

对于新创建的协程,它的CoroutineContext会包含一个全新的J0b实例,它会帮助我们控制协程的生命周期。而剩下的元素会的元素会从CoroutineContext的父类继承,该父类可能是另外一个协程或者创建该协程的CoroutineScope。

 @Test 
fun testCoroutineContextExtend() = runBlocking {
        var scope = CoroutineScope(Job() + Dispatchers.IO + CoroutineName("testExtend"))
        val launch = scope.launch {
            //launch为scope的子协程,会继承scope的上下文
            println("${coroutineContext[Job]}    ${Thread.currentThread().name}")
            val async = async {
                //async为launch的子协程,会继承scope的上下文
                println("${coroutineContext[Job]}    ${Thread.currentThread().name}")
                "OK"
            }.await()
        }
        launch.join()

    }

打印结果:

"testExtend#2":StandaloneCoroutine{Active}@6318c9c9    DefaultDispatcher-worker-1 @testExtend#2
"testExtend#3":DeferredCoroutine{Active}@11fd5300    DefaultDispatcher-worker-3 @testExtend#3

前面不同是因为,每个Job对象都不同。


协程的上下文=默认值+继承的CoroutineContext+参数
一些元素包含默认值:Dispatchers.De

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值