【问题标题】:Why when launch without delay (in Android), it didn't finish the task?为什么立即启动(在 Android 中)时,它没有完成任务?
【发布时间】: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


    【解决方案1】:

    Android 的记录器在看到两个以上连续的相同消息后会忽略重复的日志消息,并声明包是“健谈的”。

    不使用协程试试这个,你会看到:

        repeat(10) {
            Log.d("all the same", "Hello World")
        }
        repeat(10) {
            Log.d("with indices", "Hello World $it")
        }
    

    您的代码中的延迟会阻止相同的消息连续出现,因为您有两个协同程序同时记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-08
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      相关资源
      最近更新 更多