为什么当启动时没有延迟(在Android中),它没有完成任务?
我在下面有一个简单的协程实验
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]'
但是,如果我delay(1)从两者的代码中删除launch
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)
}
}
}
}
它只打印 2 次并按顺序打印launch。
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 的记录器在看到两个以上连续的相同消息后会忽略重复的日志消息,声明该包是“健谈的”。
在没有协程的情况下试试这个,你会看到:
repeat(10) {
Log.d("all the same", "Hello World")
}
repeat(10) {
Log.d("with indices", "Hello World $it")
}
代码中的延迟会阻止相同的消息连续出现,因为您有两个协程同时记录日志。