Kotlin异步与启动

so-*_*ude 5 kotlin kotlinx.coroutines

Kotlin_version ='1.2.41'

我对Kotlin很陌生。我想知道async和之间的区别launch。特别是在以下代码中

import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.awaitAll
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking

fun main(args: Array<String>) {
    runBlocking {
        (20..30).forEach {
            launch{
                println("main before" + it)
                val outer = it
                delay(1000L)
                val lists = (1..10)
                        .map { async{anotherMethod(outer, it)}}
                println("main after------------------Awaiting" + it)
                lists.awaitAll()
                println("Done awaiting -main after-----------------" + it)

            }


        }

        println("Hello,") // main thread continues here immediately
    }
}
Run Code Online (Sandbox Code Playgroud)

suspend fun anotherMethod (outer: Int,index: Int){
    println("inner-b4----" + outer + "--" + index)
    delay(3000L)
    println("inner-After----" + outer + "--" + index)
}
Run Code Online (Sandbox Code Playgroud)

VS

fun main(args: Array<String>) {
    runBlocking {
        (20..30).forEach {
            async{
                println("main before" + it)
                val outer = it
                delay(1000L)
                val lists = (1..10)
                        .map { async{anotherMethod(outer, it)}}
                println("main after------------------Awaiting" + it)
                lists.awaitAll()
                println("Done awaiting -main after-----------------" + it)

            }


        }

        println("Hello,") // main thread continues here immediately
    }
}

suspend fun anotherMethod (outer: Int,index: Int){
    println("inner-b4----" + outer + "--" + index)
    delay(3000L)
    println("inner-After----" + outer + "--" + index)
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*ene 7

async确实返回Deferred<>,而launch仅返回Job,都启动了新的协程。因此,这取决于您是否需要返回值。

在您的第一个示例中launch,不返回值-最后一个println仅产生Unit。如果async在第二个示例中使用,则总体结果将相同,但是创建了一些无用的Deferred<Unit>对象。

  • 确保不要将以上内容作为使用`async`而不是`launch`的建议。您可以提供一个异常处理程序来“启动”以使其安全。 (2认同)