生产者消费者模式Java实现

package com.szc.java;

/**
 * @Author szc
 * @Date 2021/8/24
 */
//缓冲区(售货员)
class Clerk {
    private int quantity=0;

    public int getQuantity() {
        return quantity;
    }
    //当货物数量为20(满)时,唤醒消费者进程,并使得生产者进程阻塞。
    public synchronized void Purchase(){
        notify();
        while (quantity == 20){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

            quantity++;


    }
    //当货物数量为0时,唤醒生产者进程,并使得消费者进程阻塞。
    public synchronized void Sale(){
        notifyAll();
        while (quantity == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        quantity--;




    }

}
//生产者进程
class  Producer implements Runnable{
    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {

        while (true) {

                synchronized (clerk) {
                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    clerk.Purchase();
                    int x = clerk.getQuantity();
                    System.out.println(Thread.currentThread().getName() + "生产了第" + x + "个产品");

                }


        }
    }
}
//消费者进程
class Consumer implements Runnable{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while (true) {

                synchronized (clerk) {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    clerk.Sale();
                    int x = clerk.getQuantity()+1;
                    System.out.println(Thread.currentThread().getName() + "消费了第" + x + "个产品");

                }

        }
    }
}
//主函数
public class Pipeline {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer producer = new Producer(clerk);
        Consumer consumer = new Consumer(clerk);

        Thread p1 = new Thread(producer);
        Thread c1 = new Thread(consumer);
        Thread c2 = new Thread(consumer);

        p1.setName("生产者1");
        c1.setName("消费者1");
        c2.setName("消费者2");
        p1.start();
        c1.start();
        c2.start();


    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值