fun producerConsumer() {
val content = mutableListOf<Int>()
for (i in 10 downTo 1 step 1) content.add(i)
val lockForConsumer = Object()
val lockForProducer = Object()
val consumer1 = thread {
while (true) {
synchronized(lockForConsumer) {
while (content.size > 0) {
println("Consumer1 consume content:${content[content.lastIndex]}")
content.removeAt(content.lastIndex)
lockForConsumer.notify()
Thread.sleep(1000)
lockForConsumer.wait()
}
synchronized(lockForProducer) {
lockForProducer.notifyAll()
lockForProducer.wait()
}
}
}
}
val consumer2 = thread {
while (true) {
synchronized(lockForConsumer) {
while (content.size > 0) {
println("Consumer2 consume content:${content[content.lastIndex]}")
content.removeAt(content.lastIndex)
lockForConsumer.notify()
Thread.sleep(1000)
lockForConsumer.wait()
}
synchronized(lockForProducer) {
lockForProducer.notifyAll()
lockForProducer.wait()
}
}
}
}
val producer = thread {
var round = 1
while (true) {
synchronized(lockForProducer) {
for (i in 10 downTo 1 step 1) content.add(i)
println("Producer round $round")
round++
lockForProducer.notifyAll()
lockForProducer.wait()
}
}
}
}
fun main() {
producerConsumer()
}
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme