当前位置:嗨网首页>书籍在线阅读

19-协程调度与线程

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

12.5.1 协程调度与线程

协程调度程序可以将协程限制在一个特定的线程中(或者一个线程池中),当然也可以不做任何限制,让它无约束地运行。代码如下。

fun main(args: Array<String>) = runBlocking{
    val jobs = arrayListOf<Job>()
    //无限制:在main thread中执行
    jobs += launch(Unconfined) {
     println("【Unconfined】:thread:${Thread.currentThread()}")
    }
    //父协程上下文:运行在runBlocking协程
    jobs += launch(coroutineContext) {
     println("【coroutineContext】:thread:${Thread.currentThread()}")
    }
    //调度指派给 ForkJoinPool.commonPool
    jobs += launch(CommonPool) {
     println("【CommonPool】:thread:${Thread.currentThread()}")
    }
    //协程将会工作在自定义线程中
    jobs += launch(newSingleThreadContext("SingleThread")) {
     println("【newSingleThreadContext】:thread:${Thread.currentThread()}")
    }
    jobs.forEach { it.join() }
    }

运行上面的代码,输出的结果如下。

【Unconfined】:thread:Thread[main,5,main]
【CommonPool】:thread:Thread[ForkJoinPool.commonPool-worker-1,5,main]
【newSingleThreadContext】:thread:Thread[SingleThread,5,main]
【coroutineContext】:thread:Thread[main,5,main]

使用不同的协程调度器,输出的结果和实现的功能也不一样,具体区别有以下几点。

  • 使用无限制的Unconfined定义的上下文协程运行在主线程中。
  • 继承runBlocking {...} 的coroutineContext协程则继续在主线程中运行。
  • CommonPool运行在ForkJoinPool.commonPool中。
  • 使用newSingleThreadContext函数新建的协程,直接运行在新建的线程中。