生产者和消费者模式

该示例展示了如何使用Java的wait和notify方法实现商品的生产和消费。商品类包含最大库存和当前库存,并提供了生产者和消费者线程的方法。生产者线程每秒增加一件商品,消费者线程每三秒消耗一件,当库存达到最大或为0时,线程会进行等待和唤醒操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、wait/notify实现

  • 商品类
class Goods{
    Integer maxcount;
    Integer count;

    public Goods(Integer maxcount, Integer count) {
        this.maxcount = maxcount;
        this.count = count;
    }

    public synchronized void consumers() {
        if(count>0){
            count--;
            System.out.println("消费者"+Thread.currentThread().getName()+": "+count);
            notifyAll();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void product() {
        if(count< maxcount){
            count++;
            System.out.println("生产者"+Thread.currentThread().getName()+": "+count);
            notifyAll();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 生产者线程
class Produce extends Thread{
    Goods goods;

    public Produce(Goods goods){
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true){

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            goods.product();
        }
    }
}
  • 消费者线程
class Custom extends Thread{

    Goods goods;

    public Custom(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true){

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            goods.consumers();
        }
    }
}
  • 主方法
public static void main(String[] args) {
        Goods goods = new Goods(10, 0);
        Produce produce = new Produce(goods);
        produce.setName("生产者1");
        Custom custom = new Custom(goods);
        custom.setName("消费者1");

        Custom custom2 = new Custom(goods);
        custom2.setName("消费者2");
        custom.start();
        produce.start();
        custom2.start();

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值