0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at
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()
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?