java多线程——生产者与消费者模型

一个生产者,一个消费者:

1.让生产者线程和消费者线程 共同操作同一个手机对象(资源)

2.让两个产品来回切换(目的是放大第一个步骤的问题)加锁,防止脏数据的出现

3.生产一个消费一个代码实现:

public class Test01 {
    
    public static void main(String[] args) {

        Phone phone = new Phone();
        
        Producer p = new Producer(phone);
        Consumer c = new Consumer(phone);
        
        p.start();
        c.start();
        
    }

}

package com.dream.producer_consumer01_type01;

public class Phone {
    
    private String brand;
    private double price;
    private boolean isStore;
    
    public boolean isStore() {
        return isStore;
    }

    public void setStore(boolean isStore) {
        this.isStore = isStore;
    }

    public Phone() {
        
    }

    public Phone(String brand, double price, boolean isStore) {
        super();
        this.brand = brand;
        this.price = price;
        this.isStore = isStore;
    }

    public String getBrand() {
        return brand;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Phone [brand=" + brand + ", price=" + price + ", isStore=" + isStore + "]";
    }
}
package com.dream.producer_consumer01_type01;

//生产者线程
public class Producer extends Thread{
    
    private Phone phone;
    
    public Producer(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        boolean flag = true;
        
        while(true){
            synchronized(phone){
                if(phone.isStore()){//有库存
                    
                    try {
                        phone.wait();//wait:使当前线程等待,并把等待的线程记录在对象监视器(phone)中
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                
                if(flag){
                    phone.setBrand("华为");
                    phone.setPrice(3999);
                }else{
                    phone.setBrand("小米");
                    phone.setPrice(1999);
                }
                flag = !flag;
                phone.setStore(true);//设置为有库存
                
                phone.notify();//唤醒:唤醒对象监视器中第一个等待的线程
            }
            
        }
    }
}

package com.dream.producer_consumer01_type01;

//消费者线程
public class Consumer extends Thread{
    
    private Phone phone;
    
    public Consumer(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        while(true){
            synchronized(phone){
                if(!phone.isStore()){//没有库存
                    try {
                        phone.wait();//wait:使当前线程等待,并把等待的线程记录在对象监视器(phone)中
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(phone.getBrand() + " -- " + phone.getPrice());
                phone.setStore(false);//设置成没有库存
                
                phone.notify();//唤醒:唤醒对象监视器中第一个等待的线程
            }
        }
    }
}


2.多个生产者和消费者
代码实现:

public class Test01 {
    
    public static void main(String[] args) {

        Phone phone = new Phone();
        
        Producer p1 = new Producer(phone);
        Producer p2 = new Producer(phone);
        Consumer c1 = new Consumer(phone);
        Consumer c2 = new Consumer(phone)
        
        p1.start();
        p2.start();
        c1.start();
        c2.start();
        
    }

}

package com.dream.producer_consumer01_type01;

public class Phone {
    
    private String brand;
    private double price;
    private boolean isStore;
    
    public boolean isStore() {
        return isStore;
    }

    public void setStore(boolean isStore) {
        this.isStore = isStore;
    }

    public Phone() {
        
    }

    
    public Phone(String brand, double price, boolean isStore) {
        super();
        this.brand = brand;
        this.price = price;
        this.isStore = isStore;
    }

    public String getBrand() {
        return brand;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Phone [brand=" + brand + ", price=" + price + ", isStore=" + isStore + "]";
    }
}
package com.dream.producer_consumer01_type01;

//生产者线程
public class Producer extends Thread{
    
    private Phone phone;
    
    public Producer(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        boolean flag = true;
        
        while(true){
            synchronized(phone){
                while(phone.isStore()){//有库存
                    
                    try {
                        phone.wait();//wait:使当前线程等待,并把等待的线程记录在对象监视器(phone)中
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                
                if(flag){
                    phone.setBrand("华为");
                    phone.setPrice(3999);
                }else{
                    phone.setBrand("小米");
                    phone.setPrice(1999);
                }
                flag = !flag;
                phone.setStore(true);//设置为有库存
                
                phone.notifyAll();//唤醒:唤醒对象监视器中第一个等待的线程
            }
            
        }
    }
}

package com.dream.producer_consumer01_type01;

//消费者线程
public class Consumer extends Thread{
    
    private Phone phone;
    
    public Consumer(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        while(true){
            synchronized(phone){
                while(!phone.isStore()){//没有库存
                    try {
                        phone.wait();//wait:使当前线程等待,并把等待的线程记录在对象监视器(phone)中
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(phone.getBrand() + " -- " + phone.getPrice());
                phone.setStore(false);//设置成没有库存
                
                phone.notifyAll();//唤醒:唤醒对象监视器中第一个等待的线程
            }
        }
    }
}


仓储模型
1.一个生产者一个消费者的情况
代码实现:

public class Test01 {
    
    public static void main(String[] args) {
        
        Store store = new Store();
        
        Producer p = new Producer(store);
        Consumer c = new Consumer(store);
        
        p.start();
        c.start();
    }

}
package com.dream.producer_consumer02_type01;

//蛋糕类
public class Cake {

    private String brand;
    private String dataTime;
    
    public Cake() {
    }

    public Cake(String brand, String dataTime) {
        this.brand = brand;
        this.dataTime = dataTime;
    }

    public String getBrand() {
        return brand;
    }

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

    public String getDataTime() {
        return dataTime;
    }

    public void setDataTime(String dataTime) {
        this.dataTime = dataTime;
    }

    @Override
    public String toString() {
        return "Cake [brand=" + brand + ", dataTime=" + dataTime + "]";
    }
    
}
package com.dream.producer_consumer02_type01;

import java.util.LinkedList;

//仓库类
public class Store {

    //蛋糕容器
    private LinkedList<Cake> list = new LinkedList<>();
    //最大容量
    private int maxCapacity = 20;
    //当前容量
    private int currentCapacity;
    
    //入库
    public void push(Cake cake){
        synchronized (this) {
            if(currentCapacity >= maxCapacity){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(cake);
            currentCapacity++;
            System.out.println("入库,当前容量为:" + currentCapacity);
            this.notify();
        }
        
    }
    
    //出库
    public void pop(){
        synchronized (this) {
            if(currentCapacity <= 0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Cake cake = list.removeFirst();
            currentCapacity--;
            System.out.println("出库,当前容量为:" + currentCapacity + " -- " + cake);
        
            this.notify();
        }
    }
}
package com.dream.producer_consumer02_type01;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Producer extends Thread{
    
    private Store store;
    
    public Producer(Store store) {
        this.store = store;
    }

    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while(true){
            Cake cake = new Cake("桃李面包", sdf.format(new Date()));
            store.push(cake);
        }
    }
}
package com.dream.producer_consumer02_type01;

public class Consumer extends Thread{
    
    private Store store;
    
    public Consumer(Store store) {
        this.store = store;
    }

    @Override
    public void run() {
        while(true){
            store.pop();
        }
    }
}



2.多个生产者和消费者
代码实现:

public class Test01 {
    
    public static void main(String[] args) {
        
        Store store = new Store();
        
        Producer p1 = new Producer(store);
        Producer p2 = new Producer(store);
        Consumer c1 = new Consumer(store);
        Consumer c2 = new Consumer(store);
        
        p1.start();
        p2.start();
        c1.start();
        c2.start();
    }

}
package com.dream.producer_consumer02_type01;

//蛋糕类
public class Cake {

    private String brand;
    private String dataTime;
    
    public Cake() {
    }

    public Cake(String brand, String dataTime) {
        this.brand = brand;
        this.dataTime = dataTime;
    }

    public String getBrand() {
        return brand;
    }

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

    public String getDataTime() {
        return dataTime;
    }

    public void setDataTime(String dataTime) {
        this.dataTime = dataTime;
    }

    @Override
    public String toString() {
        return "Cake [brand=" + brand + ", dataTime=" + dataTime + "]";
    }
    
}
package com.dream.producer_consumer02_type01;

import java.util.LinkedList;

//仓库类
public class Store {

    //蛋糕容器
    private LinkedList<Cake> list = new LinkedList<>();
    //最大容量
    private int maxCapacity = 20;
    //当前容量
    private int currentCapacity;
    
    //入库
    public void push(Cake cake){
        synchronized (this) {
            while(currentCapacity >= maxCapacity){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(cake);
            currentCapacity++;
            System.out.println("入库,当前容量为:" + currentCapacity);
            this.notifyAll();
        }
        
    }
    
    //出库
    public void pop(){
        synchronized (this) {
            while(currentCapacity <= 0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Cake cake = list.removeFirst();
            currentCapacity--;
            System.out.println("出库,当前容量为:" + currentCapacity + " -- " + cake);
        
            this.notifyAll();
        }
    }
}
package com.dream.producer_consumer02_type01;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Producer extends Thread{
    
    private Store store;
    
    public Producer(Store store) {
        this.store = store;
    }

    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while(true){
            Cake cake = new Cake("桃李面包", sdf.format(new Date()));
            store.push(cake);
        }
    }
}
package com.dream.producer_consumer02_type01;

public class Consumer extends Thread{
    
    private Store store;
    
    public Consumer(Store store) {
        this.store = store;
    }

    @Override
    public void run() {
        while(true){
            store.pop();
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值