0
Help us understand the problem. What are the problem?

posted at

Kotlinで「生産者消費者」の実現

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()
}

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?