kotlin: CoroutineContext 协程上下文

一,CoroutineContext 协程上下文包含哪些元素?

  • Job:控制协程的生命周期。
  • CoroutineDispatcher: 指定分发任务的线程,这一项就是我们已经介绍过的调度器:Dispatchers。默认值是 Dispatchers.Default。
  • CoroutineName:指定协程的名称,这一项在调试时比较有用。默认值是 "coroutine"。
  • CoroutineExceptionHandler: 指定未被捕获的异常的处理器。

二,协程上下文的继承

代码:

        //处理按钮点击事件
        binding.button1.setOnClickListener {
            runBlocking {

                val scope = CoroutineScope(Job() + Dispatchers.IO + CoroutineName("test"))
                val job = scope.launch {
                    println("launch ${coroutineContext[Job]} ${coroutineContext[CoroutineName]} ${Thread.currentThread().name}")
                    launch {
                        println("launch child 1: ${coroutineContext[Job]} ${coroutineContext[CoroutineName]} ${Thread.currentThread().name}")
                    }
                    launch {
                        println("launch child 2: ${coroutineContext[Job]} ${coroutineContext[CoroutineName]} ${Thread.currentThread().name}")
                    }
                }
                job.join()

            }
        }

运行结果:

image

说明:可以看到父协程和子协程的Job 对象各不相同,但 CorountineName 是相同的,
         因为两个子协程的 CoroutineName 都是从父类继承而来。

posted @ 2025-08-09 13:40  刘宏缔的架构森林  阅读(7)  评论(0)    收藏  举报