由于源代码中有多个实现,异步无法编译
Async won't compile because of multiple implementations in source
我正在尝试 运行 以下代码,但它不是 运行ning,因为编译器不知道要调用哪个版本的 async
方法。我如何告诉它调用哪一个?
v
ar counter=0
val workerA=asyncIncrement(5000)
val workerB=asyncIncrement(100)
workerA.await()
workerB.await()
print("counter = $counter")
fun asyncIncrement(by:Int)=async{
for(i in 1..by){
counter++
}
}
只需将代码复制并粘贴到临时文件或任何地方,您应该会看到相同的编译器错误
从 Kotlin 1.3 开始,您需要在作用域上调用 async
。在这个例子中我选择了
GlobalScope
。但无论您选择哪个范围,您始终必须显式导入 async
扩展函数;
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
fun main(args: Array<String>) {
val counter=AtomicInteger(0)
fun asyncIncrement(by:Int)= GlobalScope.async{
for(i in 1..by){
counter.incrementAndGet()
}
}
val workerA=asyncIncrement(5000)
val workerB=asyncIncrement(100)
runBlocking {
workerA.await()
workerB.await()
}
print("counter = $counter")
}
顺便说一句:
我将变量 counter
从 int
更改为 AtomicInteger
因为两个 async
块可能 运行 在不同的线程中。我引入了 runBlocking
,因为 await
必须在挂起函数中 运行。
我正在尝试 运行 以下代码,但它不是 运行ning,因为编译器不知道要调用哪个版本的 async
方法。我如何告诉它调用哪一个?
v
ar counter=0
val workerA=asyncIncrement(5000)
val workerB=asyncIncrement(100)
workerA.await()
workerB.await()
print("counter = $counter")
fun asyncIncrement(by:Int)=async{
for(i in 1..by){
counter++
}
}
只需将代码复制并粘贴到临时文件或任何地方,您应该会看到相同的编译器错误
从 Kotlin 1.3 开始,您需要在作用域上调用 async
。在这个例子中我选择了
GlobalScope
。但无论您选择哪个范围,您始终必须显式导入 async
扩展函数;
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
fun main(args: Array<String>) {
val counter=AtomicInteger(0)
fun asyncIncrement(by:Int)= GlobalScope.async{
for(i in 1..by){
counter.incrementAndGet()
}
}
val workerA=asyncIncrement(5000)
val workerB=asyncIncrement(100)
runBlocking {
workerA.await()
workerB.await()
}
print("counter = $counter")
}
顺便说一句:
我将变量 counter
从 int
更改为 AtomicInteger
因为两个 async
块可能 运行 在不同的线程中。我引入了 runBlocking
,因为 await
必须在挂起函数中 运行。