协程之间的通讯
@Test
fun `test know chanel`() = runBlocking<Unit> {
val channel = Channel<Int>()
//生产者
val peoducer = GlobalScope.launch {
var i = 0
while (true) {
delay(1000)
channel.send(++i)
println("send $i")
}
}
val consumer = GlobalScope.launch {
while (true) {
val element = channel.receive()
println("receive $element")
}
}
joinAll(peoducer,consumer)
}
Channel实际上是一个并发安全的队列,它可以用来链接携程,实现不同携程的通信
Channel 也会有容量
如果消费者接受时间比较慢。。
那么会按照接受者的时间来吐出来元素
如何遍历Channel
先全部添加,然后在慢慢取出来
@Test
fun `test iterate channel`() = runBlocking<Unit> {
val channel = Channel<Int>(Channel.UNLIMITED)
//生产者
val producer = GlobalScope.launch {
for (x in 1..5) {
channel.send(x * x)
println("send ${x * x}")
}
}
val consumer = GlobalScope.launch {
val iterator = channel.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
println("receive ${element}")
delay(2000)
}
}
joinAll(producer, consumer)
}