【发布时间】:2021-01-29 07:28:05
【问题描述】:
首先,大家好,我是新来的。今天我只是在玩 Kotlin Coroutines 和 Channels。从官方文档中,我看到了这样一个频道的代码 sn-p:
val channel = Channel<Int>()
launch {
// this might be heavy CPU-consuming computation or async logic, we'll just send five squares
for (x in 1..5) channel.send(x * x)
}
// here we print five received integers:
repeat(5) { println(channel.receive()) }
println("Done!")
然后我决定在 Kotlin Playground 中运行这个 sn-p 并进行一些修改,这样我就可以知道有多少 coroutines 正在工作。
我的代码:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun log(msg1:String ,msg2: Int) = println("[${Thread.currentThread().name}] $msg1 $msg2")
fun main() = runBlocking {
val channel = Channel<Int>();
launch {
for (x in 1..5) {
channel.send(x * x)
log("sending",x*x)
}
}
repeat(5){log("receiving",channel.receive())}
println("Done!")
}
不出所料,我收到了输出:
[main @coroutine#2] sending 1
[main @coroutine#1] receiving 1
[main @coroutine#1] receiving 4
[main @coroutine#2] sending 4
[main @coroutine#2] sending 9
[main @coroutine#1] receiving 9
[main @coroutine#1] receiving 16
[main @coroutine#2] sending 16
[main @coroutine#2] sending 25
[main @coroutine#1] receiving 25
Done!
但是当我在 YouTube 上观看 Kotlin 会议时,我尝试启动单独的 CoroutineScope,其中“Roman Elizarov”说明我们可以在不同 CoroutineScope 的通道之间传输数据。所以,我尝试了这个:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun log(msg1:String ,msg2: Int) = println("[${Thread.currentThread().name}] $msg1 $msg2")
fun main() = runBlocking {
val channel = Channel<Int>();
launch {
for (x in 1..5) {
channel.send(x * x)
log("sending",x*x)
}
}
CoroutineScope{
launch{log("receiving",channel.receive())}
}
println("Done!")
}
运行此程序后,我收到Type mismatch: inferred type is () -> Job but CoroutineContext was expected 的错误
这是我试图纠正这个错误的方法:我添加了Dispatchers.Default
CoroutineScope{
launch(Dispatchers.Default){log("receiving",channel.receive())}
}
抛出同样的错误。为幼稚的代码道歉。
有人可以帮忙吗?
【问题讨论】:
标签: multithreading kotlin kotlin-coroutines