• Kotlin 设置和获取协程名称


    1,设置写成名称

    创建协程作用域是或者创建协程是有个上下文参数(context: CoroutineContext)

    创建协程作用域

    CoroutineScope(Dispatchers.IO + CoroutineName("协程A"))//Dispatchers.IO根据实际情况设置可有可无

    源码:

    public fun CoroutineScope(context: CoroutineContext): CoroutineScope = ContextScope(if (context[Job] != null) context else context + Job())

    创建协程的launch函数

    GlobalScope.launch(Dispatchers.IO + CoroutineName("协程A")){//Dispatchers.IO根据实际情况设置可有可无, }

    源码

    public fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit )//注意函数前两个参数有默认值

    由于CoroutineContext重写了+号,所以创建协程作用域或者创建协程的时候可以通过 Dispatchers.IO + CoroutineName("协程A")为函数context: CoroutineContext参数传递值;

    2,获取协程名称
    1. CoroutineScope(Dispatchers.IO + CoroutineName("协程A")).launch {
    2. Log.d(TAG, "当前线程和协程1: ${Thread.currentThread().name} + ${coroutineContext[CoroutineName]?.name}")
    3. runBlocking(CoroutineName("协程B")){ //runBlocking阻塞协程所在的线程2秒,因为此协程作用域内代码需要2秒才能执行完成
    4. Log.d(TAG, "当前线程和协程: ${Thread.currentThread().name} ${coroutineContext[CoroutineName]?.name}")
    5. delay(1000.times(2)) //挂起函数,非阻塞式,挂起当前协程2
    6. }
    7. Log.d(TAG,"当前线程和协程2:${Thread.currentThread().name} + ${coroutineContext[CoroutineName]?.name}")
    8. }

    在协程内部调用如下API即可获取到协程名称

    coroutineContext[CoroutineName]?.name

  • 相关阅读:
    【kafka实战】03 SpringBoot使用kafka生产者和消费者示例
    http2流分片data数据合并-linux xxd方法
    js的同步执行
    KASan介绍
    linux安装Sentinal1.8.6
    (十四)线程(基础)
    Linux——操作进程状态
    会议OA(会议排座&送审)
    SpringBoot实现多数据源(六)【dynamic-datasource 多数据源组件】
    重新理解 RocketMQ Commit Log 存储协议
  • 原文地址:https://blog.csdn.net/ezconn/article/details/133916308