zl程序教程

您现在的位置是:首页 >  其它

当前栏目

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

一个 模型 生产 消费 消费者 生产者 随手 偷懒
2023-06-13 09:14:08 时间

「Talk is cheap. Show me the code」

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

一次成功还是蛮高兴的