Java(线程)生产者与消费者

Java(线程)生产者与消费者,第1张

 生产者与消费者问题(同步,等待与唤醒)

 出现问题:
     1、生产者未生产商品,消费者就消费了;
      2、消费者消费一次后,已经不存在商品了,再次消费;
      3、连续生产,连续消费;
      4、消费者消费的时候,会出现商品的两个属性不能正确对应。  --->  使用同步解决商品属性不对应问题
消费者取出商品(拿商品)
public class Consumer  implements Runnable {

    private Goods goods;

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

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            goods.get();
        }
    }       
}
生产者负责生产商品
public class Producer implements Runnable {

    private Goods goods;

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

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            //交替生产两种商品
            if(i % 2 == 0){
                goods.set("农夫山泉","饮用天然水");
            }else{
                goods.set("百岁山","天然矿泉水");
            }
        }
    }
}
共享资源:商品
public class Goods {

    private String brand;
    private String name;

    public Goods() {
    }

    public Goods(String brand, String name) {
        this.brand = brand;
        this.name = name;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //生产商品
    public synchronized void set(String brand,String name){
        this.setBrand(brand);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setName(name);
        System.out.println("生产者生产了-------" + this.getBrand() + "-----" +this.getName());
    }

    //消费商品
    public synchronized void get(){
        //消费商品
        System.out.println("消费者消费了========" +this.getBrand() + "========" + this.getName());
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
测试类
public class Test1 {

    public static void main(String[] args) {
        Goods goods = new Goods();
        Producer producer = new Producer(goods);
        Consumer consumer = new Consumer(goods);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

运行图

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/736235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存