我正在从事过程导向编程的课程。
我正在尝试在协程中启动两个对象(生产者和消费者),然后让生产者消费。然后我告诉main函数等待coroutine完成Job.join()。但是,这似乎不起作用。因为invokeOnCompletion函数是在生产/消费周期开始之前执行的。我已经包含了下面的代码和输出,并将欣赏任何输入。
这是面向过程编程的课程。最终目标是生成多个对象实例并让它们使用通道进行通信。我以前从未在kotlin中编写代码,也从未使用过协程。这甚至是可能的,还是我误解了协同程序?
class Producer(val idvar: Int) {
var resource: Int = 10
init {
println("${idvar} was created.")
}
suspend fun getConsumed(channel: Channel<Int>) = produce<Int> {
println("Someone is trying to consume me...")
while(true) {
channel.send(1)
resource--
println("I have ${resource} things left.")
if(resource <= 0) {
break
}
var sleep = ((Random().nextDouble())*1000).toLong()
println("sleeping for ${sleep} ms")
delay(1000)
}
println("I'm used up! I have ${resource} resources.")
}
}
class Consumer() {
var resource: Int = 0
suspend fun consume(producer: Producer?, channel: Channel<Int>) = produce<Int> {
println("Trying to consume producer: ${producer?.resource}")
producer?.getConsumed(channel)
while(true) {
var recv = channel.receive()
if(recv == 0) break
resource += recv
}
println("Consumed in total: " + resource)
}
}
fun main(args: Array<String>) = runBlocking<Unit> {
val prodJob = launch {
var prodObj: Producer = Producer(1)
var consumObj: Consumer = Consumer()
val chan = Channel<Int>()
consumObj.consume(prodObj, chan)
// Why does this println print before the above line is complete?
println("Comsumption done.")
}
// invokeOnCompletion is executed before production/consumption is done?
prodJob.invokeOnCompletion { println("Consumption is done?") }
// Main could do other stuff here.
// Since prodJob is regarded as complete, main joins instantly.
prodJob.join()
println("Joined...")
}
输出结果为:
1 was created.
Comsumption done.
Trying to consume producer: 10
Consumption is done?
Someone is trying to consume me...
I have 9 things left.
sleeping for 310 ms
Joined...
答案 0 :(得分:0)
Consumer.consume()
- 方法不正确。删除=produce<Int>
部分,它将起作用:
suspend fun consume(producer: Producer?, channel: Channel<Int>) {
println("Trying to consume producer: ${producer?.resource}")
producer?.getConsumed(channel)
while(true) {
var recv = channel.receive()
if(recv == 0) break
resource += recv
}
println("Consumed in total: " + resource)
}
BTW:Producer.getConsumed()
- 方法以错误的方式使用=produce<Int>
。 produce
创建一个从未使用过的新频道。由于produce
- 方法的一些内部实现细节,它才恰好工作。您应该使用launch
明确地启动第二个Coroutine。
suspend fun getConsumed(channel: Channel<Int>) = launch {
println("Someone is trying to consume me...")
while(true) {
channel.send(1)
resource--
println("I have ${resource} things left.")
if(resource <= 0) {
break
}
var sleep = ((Random().nextDouble())*1000).toLong()
println("sleeping for ${sleep} ms")
delay(1000)
}
println("I'm used up! I have ${resource} resources.")
}