随手写了一个偷懒版的生产者消费者模型(多生产多消费)

2022-10-27 16:06:17 浏览数 (2)

「Talk is cheap. Show me the code」

代码语言:javascript复制
package com.jmy.consumer;


import java.util.Random;


/*
简单的生产者消费者案例
 */
public class ConsumerDemo {
    public static void main(String[] args) {
        Product p = new Product();
        new Thread(new Consumer(p)).start();
        new Thread(new Productor(p)).start();
        new Thread(new Consumer(p)).start();
        new Thread(new Productor(p)).start();
        new Thread(new Consumer(p)).start();
        new Thread(new Productor(p)).start();
        new Thread(new Consumer(p)).start();
        new Thread(new Productor(p)).start();
    }
}

// 商品类
class Product {
    // 剩余库存
    public int count;
    // 标记值
    public boolean flag;
}
// 生产者线程类
class Productor implements Runnable{

    Product product;

    public Productor(Product product) {
        this.product = product;
    }

    @Override
    public void run() {

        // 无限生产
        while (true) {
            synchronized ("锁") {
                while (product.flag) {
                    try {
                        "锁".wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                // 库存不可超过1000
                int count =  - product.count;
                // 随机生产
                int i = new Random().nextInt(count   );
                product.count = product.count   i;
                System.out.println("本次生产:"   i   "  剩余库存:"   product.count);

                product.flag = true;
                "锁".notifyAll();
            }
        }
    }
}
 class Consumer implements Runnable{

     Product product;

     public Consumer(Product product) {
         this.product = product;
     }
     @Override
     public void run() {
         // 无限消费
         while (true) {
             synchronized ("锁") {
                 while (!product.flag) {
                     try {
                         "锁".wait();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }

                 int count = product.count;
                 int i = new Random().nextInt(count   );
                 product.count = product.count - i;
                 System.out.println("本次消费:"   i   " 剩余库存:"   product.count);

                 product.flag = false;
                 "锁".notifyAll();
             }
         }
     }
 }

一次成功还是蛮高兴的

0 人点赞