Android 协程 async 并发执行

默认情况下。他们的顺序执行的

        runBlocking {
                val time1 = measureTimeMillis {
                    val one = doOne()
                    val two = doTwo()
                    Log.e(TAG, "the 1 result:${one + two}")
                }
                Log.e(TAG, "Completed 1 in $time1 ms")
        }

如何改为并发执行呢?

        binding.btClick6.setOnClickListener {
            runBlocking {
          

                val time2 = measureTimeMillis {
                    val one = async { doOne() }
                    val two = async { doTwo() }
                    Log.e(TAG, "the 2 result:${one.await() + two.await()}")
                }
                Log.e(TAG, "Completed 2 in $time2 ms")

            }
        }

使用async

但是千万不要使用这种写法

    //错误示范
                val time3 = measureTimeMillis {
                    val one = async { doOne() }.await()
                    val two = async { doTwo() }.await()
                    Log.e(TAG, "the 3 result:${one + two}")
                }
                Log.e(TAG, "Completed 3 in $time3 ms")

否则还会是2s

扫描二维码关注公众号,回复: 14261009 查看本文章

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/125241165