java中的生产者和消费者

生产者和消费者

1、分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x3pXftMh-1616301860105)(E:\大数据学习\开课吧学习\第四章\多线程\生产者与消费者.png)]

1、我们有一个共用的食物类
2、厨师可以生产这个食物
3、消费者可以消费食物
4、有食物,才能消费,所以消费的前提是食物数量比0大
5、没有食物,那就要生产,但是上限为10个,生产了10个就达到上限,不生产了

2、案例

Food食物类

public class Food {
    private int count = 0;

    private final int capacity = 10;

    public synchronized void produceFood() {
        while (true) {
            System.out.println("---------");
            if(count < capacity) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                System.out.println("生产了食物,现在食物有:" + count);
                this.notifyAll();
            } else {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized void customeFood() {
        while (true) {
            if(count > 0) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
                System.out.println("食物消费成功,剩余食物为:" + count);
                this.notifyAll();
            } else {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

Cooker类

public class Cooker implements Runnable {
    private Food f;

    public Cooker() {}

    public Cooker(Food f) {
        this.f = f;
    }

    @Override
    public void run() {
        cook();
    }

    public void cook() {
        f.produceFood();
    }
}

Customer类

public class Customer implements Runnable {
    private Food f;
    public Customer() {}
    public Customer(Food f) {
        this.f = f;
    }
    @Override
    public void run() {
        custom();
    }

    public void custom() {
        f.customeFood();
    }

}

测试类

public class Test {
    public static void main(String[] args) {
        Food f = new Food();
        Cooker cooker = new Cooker(f);
        Customer customer = new Customer(f);
        new Thread(cooker).start();
        new Thread(customer).start();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值