kotlin - Kotlin 异步与启动
问题描述
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
}
}
.
suspend fun anotherMethod (outer: Int,index: Int){
println("inner-b4----" + outer + "--" + index)
delay(3000L)
println("inner-After----" + outer + "--" + index)
}
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)
}
解决方案
async
确实返回 a Deferred<>
,而launch
只返回 a Job
,都开始一个新的协程。所以这取决于你是否需要返回值。
在您的第一个示例中,launch
不返回值 - 最后一个println
仅产生Unit
. 如果你async
在第二个例子中使用 as,总体结果将是相同的,但是你创建了一些无用的Deferred<Unit>
对象。
推荐阅读
- ruby-on-rails - 如何使用 postgis 为 rails 应用程序配置 heroku ci?
- python - 如何分组和应用自定义聚合函数来获取熊猫列的模式值?
- android - 什么是在 Android Studio 中的模块 classes.jar 错误中发现的重复类(尝试连接到 Firebase 时)以及如何解决?
- java - 线程问题 - 收件人在发件人之前打印
- python - 如何将用户名显式设置为python请求
- bash - 从 bash 字符串获取(不切割)特定子字符串
- sql-server - 在 MS SQL Server 中实现 geometry_columns 视图
- c# - c#: Datagrid:通过 DataTriggers 更改选择的前景色
- c# - 另一种让鼠标点击的方法?
- javascript - 网页将在 Microsoft Edge 中加载外部 CSS 和 JS,但不会在 Chrome 中