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

21-协程与线程调试

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

12.5.3 协程与线程调试

协程可以在一个线程上挂起,也可以在另一个线程上使用Unconfined调度程序,还可以使用CommonPool这样的多线程调度来恢复协程。但是,对于协程的调度和恢复过程我们并不是很清楚,除了使用日志方式,另一种常见的方式就是使用Kotlinx.coroutines调试工具。

使用“-Dkotlinx.coroutines.debug”JVM调试选项运行如下代码。

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun main(args: Array<String>) = runBlocking<Unit> {
    val a = async(coroutineContext) {
        log("I'm computing a piece of the answer")
        6
    }
    val b = async(coroutineContext) {
        log("I'm computing another piece of the answer")
        7
    }
    log("The answer is ${a.await() * b.await()}")
}

上面的实例包含3个协程,主协程runBlocking和两个协程延迟计算值a和b,它们运行在runBlocking的上下文中,并且被限制在主线程中。运行上面的代码,输出的调试结果如下。

[main @coroutine#2] I'm computing a piece of the answer
[main @coroutine#3] I'm computing another piece of the answer
[main @coroutine#1] The answer is 42