深色模式
IDEA(Android Studio) 调试协程
打印
每一个协程上下文,都有一个CoroutineName
元素,代表此协程的名称,用于调试。要打印协程名,需求加一个JVM参数:-Dkotlinx.coroutines.debug
,然后打印线程名,此时会自动带上协程名。
添加-Dkotlinx.coroutines.debug
参数的方式:
举个🌰:
批量创建20个协程,并在这些协程中打印线程名
kotlin
fun main() = runBlocking {
repeat(20) {
launch(Dispatchers.Default) {
delay(1500)
println("job on [${Thread.currentThread().name}]")
}
}
}
不加-Dkotlinx.coroutines.debug
参数时,运行结果:
job on [DefaultDispatcher-worker-3]
job on [DefaultDispatcher-worker-2]
job on [DefaultDispatcher-worker-4]
job on [DefaultDispatcher-worker-6]
job on [DefaultDispatcher-worker-8]
job on [DefaultDispatcher-worker-5]
job on [DefaultDispatcher-worker-8]
job on [DefaultDispatcher-worker-7]
job on [DefaultDispatcher-worker-1]
job on [DefaultDispatcher-worker-8]
job on [DefaultDispatcher-worker-7]
job on [DefaultDispatcher-worker-5]
job on [DefaultDispatcher-worker-3]
job on [DefaultDispatcher-worker-5]
job on [DefaultDispatcher-worker-6]
job on [DefaultDispatcher-worker-4]
job on [DefaultDispatcher-worker-2]
job on [DefaultDispatcher-worker-7]
job on [DefaultDispatcher-worker-8]
job on [DefaultDispatcher-worker-1]
加-Dkotlinx.coroutines.debug
参数后,运行结果:
job on [DefaultDispatcher-worker-2 @coroutine#6]
job on [DefaultDispatcher-worker-7 @coroutine#9]
job on [DefaultDispatcher-worker-1 @coroutine#8]
job on [DefaultDispatcher-worker-4 @coroutine#3]
job on [DefaultDispatcher-worker-7 @coroutine#10]
job on [DefaultDispatcher-worker-6 @coroutine#5]
job on [DefaultDispatcher-worker-3 @coroutine#4]
job on [DefaultDispatcher-worker-8 @coroutine#2]
job on [DefaultDispatcher-worker-3 @coroutine#14]
job on [DefaultDispatcher-worker-5 @coroutine#7]
job on [DefaultDispatcher-worker-3 @coroutine#17]
job on [DefaultDispatcher-worker-6 @coroutine#16]
job on [DefaultDispatcher-worker-3 @coroutine#18]
job on [DefaultDispatcher-worker-5 @coroutine#19]
job on [DefaultDispatcher-worker-7 @coroutine#15]
job on [DefaultDispatcher-worker-6 @coroutine#20]
job on [DefaultDispatcher-worker-4 @coroutine#11]
job on [DefaultDispatcher-worker-1 @coroutine#13]
job on [DefaultDispatcher-worker-2 @coroutine#12]
job on [DefaultDispatcher-worker-8 @coroutine#21]
断点
新版本的协程库,在断点的时候,可以在Debug视图中查看协程相关信息。
界面截图不贴了。