前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >随手写了一个偷懒版的生产者消费者模型(多生产多消费)

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

作者头像
姜同学
发布2022-10-27 16:06:17
1800
发布2022-10-27 16:06:17
举报
文章被收录于专栏:姜同学姜同学

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

一次成功还是蛮高兴的

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-08-06T,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档