【发布时间】:2020-12-26 00:09:36
【问题描述】:
下面有一个简单的协程实验
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking {
launch {
repeat(5) {
Log.d("Track", "First, current thread: ${Thread.currentThread()}'")
delay(1)
}
}
launch {
repeat(5) {
Log.d("Track", "Second, current thread: ${Thread.currentThread()}'")
delay(1)
}
}
}
}
这将打印全部 5 次,或者同时打印 launch。
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
但是,如果我从 launch 的代码中删除 delay(1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking {
launch {
repeat(5) {
Log.d("Track", "First, current thread: ${Thread.currentThread()}'")
// delay(1)
}
}
launch {
repeat(5) {
Log.d("Track", "Second, current thread: ${Thread.currentThread()}'")
// delay(1)
}
}
}
}
对于launch,它只会按顺序打印 2 次。
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: First, current thread: Thread[main @coroutine#2,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
Track: Second, current thread: Thread[main @coroutine#3,5,main]'
为什么它没有完成所有 5 次循环?
注意事项在单元测试中运行时效果很好(非 Android 环境,即所有 5 次都打印出来)
【问题讨论】:
标签: android multithreading kotlin kotlin-coroutines