多线程并发环境生产者-消费者,kotlin

多线程并发环境生产者-消费者,kotlin

多个生产者-多个消费者,消费者竞争抢占生产者制造的资源。

//存放资源的仓储
val store = arrayOfNulls<Int>(1)

//资源
var RESOURCE: Int = 0

fun producer(tid: Long) {
    synchronized(store) {
        if (isFull()) {
            return
        }

        println("生产->$RESOURCE $tid @${System.currentTimeMillis()}")
        store[0] = RESOURCE //生产的资源

        RESOURCE++
    }
}

fun consumer(tid: Long) {
    synchronized(store) {
        if (!isFull()) {
            return
        }

        val i = store[0]
        println("消费<-$i $tid @${System.currentTimeMillis()}")
        store[0] = null //资源被消耗
    }
}

fun isFull(): Boolean {
    return store[0] != null
}

fun go() {
    //多个消费者,竞争消耗资源
    for (i in 0 until 5) {
        object : Thread() {
            override fun run() {
                while (true) {
                    sleep(3)

                    consumer(this.threadId())
                }
            }
        }.start()
    }

    //多个生产者
    for (i in 0 until 5) {
        val t = object : Thread() {
            override fun run() {
                while (true) {
                    sleep(3)

                    producer(this.threadId())
                }
            }
        }
        t.start()
    }
}

fun main(args: Array<String>) {
    go()
}

生产->0 31 @1680141217600
消费<-0 26 @1680141217600
生产->1 30 @1680141217600
消费<-1 24 @1680141217604
生产->2 28 @1680141217605
消费<-2 26 @1680141217605
生产->3 30 @1680141217605
消费<-3 24 @1680141217607
生产->4 31 @1680141217608
消费<-4 26 @1680141217608
生产->5 32 @1680141217608
消费<-5 27 @1680141217608
生产->6 30 @1680141217608
消费<-6 23 @1680141217610
生产->7 31 @1680141217611
消费<-7 27 @1680141217612
生产->8 29 @1680141217612
消费<-8 25 @1680141217613
生产->9 32 @1680141217614
消费<-9 26 @1680141217614
生产->10 28 @1680141217614
消费<-10 27 @1680141217615
生产->11 29 @1680141217615
消费<-11 25 @1680141217616
生产->12 31 @1680141217617
消费<-12 27 @1680141217618
生产->13 29 @1680141217619
消费<-13 25 @1680141217619
生产->14 28 @1680141217620
消费<-14 26 @1680141217620
生产->15 31 @1680141217620
消费<-15 27 @1680141217622
生产->16 29 @1680141217623
消费<-16 25 @1680141217623

Java线程同步:生产者-消费者 模型(代码示例)_zhangphil的博客-CSDN博客public class ThreadSyn {public static void main(String[] args) {new ThreadSyn();}public ThreadSyn() {Queue queue = new Queue();Producter p = new Producter(queue);Consumer c = newhttps://blog.csdn.net/zhangphil/article/details/43800967

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/129845913
今日推荐