生产消费多线程的模式代码

本文通过Java实现了一个生产者消费者模型,展示了在一个线程中生产商品,另一个线程消费商品的过程。在单生产者单消费者场景下,详细阐述了如何使用synchronized关键字和wait/notify机制保证数据的一致性。同时,扩展到多生产者多消费者情况,介绍了如何避免资源竞争,确保生产与消费的平衡。仓储模型的案例进一步解释了如何控制库存,确保不超过最大容量并防止死锁。

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

知识点:生产者消费者模型
注意:一个生产者一个消费者的情况
需求:生产一个消费一个
步骤:
1.让生产者线程和消费者线程 共同操作同一个电脑对象(资源)
2.让两个产品来回切换(目的是放大第一个步骤的问题)
加锁,防止脏数据的出现
3.生产一个消费一个

public class computer{
	//定义属性
	private String brand;
	private double price;
	private boolean isStore;//判断是否有库存

	public computer{}
	@Override
	public computer(String brand, double price){
		this.brand=brand;
		this.price=price;
	}

	public void getBrand(){return brand;}

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

	public void getPrice(){return price;}

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

	public void isStore(){return isStore;}

	public void setStore(Boolean store){isStore=store;}

}
public class Producer{
	private Computer computer;
	public Producer(Computer computer){this.computer=computer;}
	@Override
	public void run(){
		boolean flag=true;
		while(ture){
			synchronized(computer){
				try{
					computer.wait();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			if(flag){
				computer.setBrand("华硕");
				computer.setPrice(6999);
			}else{
				computer.setBrand("联想");
				computer.setPrice(7999);
			}
			flag!=flag;//置反
			computer.setStore(true);//设置成有库存
			computer.notify();//唤醒
		}
	} 
}
public class Consumer{
	private Computer computer;
	public Consumer(Computer computer){
		this.computer=computer;
	}

	@Override
	public void run(){
		while(true){
			synchronized(computer){
				if(!computer.isStore){
					try{
						computer.wait();
					}catch(InterruptedException e){
						e.printStackTrace();
					}
				}
				System.out.println(computer.getBrand()+"----"+computer.getPrice());
				computer.setStore(false);
				computer.notify();
			}
		}
	}
}
public class Test{
	public static void main(String[] args){
        Computer computer=new Computer();
        Producer p=new Producer(computer);
        Consunmer c=new Consunmer(computer);
        p.start();
        c.start();
    }
}
	 * 知识点:生产者消费者模型
	 * 
	 * 注意:多个生产者多个消费者的情况
	 * 
	 * 需求:生产一个消费一个
	 * 
	 * 步骤:
	 * 		1.让生产者线程和消费者线程 共同操作同一个电脑对象(资源)
	 * 		2.让两个产品来回切换(目的是放大第一个步骤的问题)
	 * 			加锁,防止脏数据的出现
	 * 3.生产一个消费一个
public class Computer{
    private String brand;
    private double price;
    private boolean isStore;
    
    public Computer(String brand,double price){
        this.brand=brand;
        this.price=price;
    }
    
    public void getBrand(){return brand;}
    public void setBrand(String brand){this.brand=brand;}
    
    public void getPrice(){return price;}
    public void setPrice(double price){this.price=price;}
    
    public void isStore(){return isStore;}
    public void setStore(boolean store){isStore=store;}
}
public class Producer{
    private Computer computer;
    public Producer(Computer computer){this.computer=computer;}
    @Override
    public void run(){
		int flag=true;
        while(true){
            synchronized(computer){
                while(computer.isStore){
                	try{
                    	computer.wait();//等待
                	}catch(InterruptedException e){
                    	e.printStackTrace(); 
                	}
                }
                if(flag){
                    computer.getBrand("机械革命师");
                    computer.getPrice(6999);
                }else{
                    computer.getBrand("华硕");
                    computer.getPrice(9999);
                }
                flag!=flag;
                computer.setStore(true);
                computer.notifyAll();//唤醒
            }
        }
    }
}
public class Consunmer{
    private Computer computer;
    public Consunmer(Computer computer){
        this.computer=computer;
    }
    @Override
    public void run(){
        while(true){
            synchronized(computer){
                while(!computer.isStore){
                    try{
                        computer.wait();
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
                System.out.println(computer.getBrand()+"-------"+computer.getPrice());
                computer.setStore(false);
                computer.notifyAll();
            }
        }
    }
}
public class Test{
    public static void main(String[] args){
        Computer computer=new Computer();
        Consunmer c1=new Consunmer(computer);
        Producer  p1=new Producer(computer);
        Consumer  c2=new Consunmer(computer);
        Producer  p2=new Producer(computer);
        c1.start();
        c2.start();
        p1.start();
        p2.start();
    }
}
  • 知识点:仓储模型

  • 注意:一个生产者和一个消费者

public class Cake{
 private String brand;
 private String DataTime;

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

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

 public void getDataTime(){ruturn DataTime;}
 public void setDataTime(String DataTime){this.DataTime=DataTime;}

}
public class Producer{
	private Store store;
 public Producer(Store store){
     this.store=store;
 }
 @Override
 public void run(){
     SimpleDateFromat sdf=new SimpleDateFromat("yyyy-MM-dd HH:mm:ss");
     while(true){
         Cake cake=new Cake("樱樱面包",sdf.format(new Date()));
         store.push(cake);
     }
 }

}
public class Consumer{
 private Store store;
 public Consumer(Store store){
     this.store=store;
 }
 @Override
 public void run(){
     while(true){
         store.pop();
     }
 }
}
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);
            currentCacity++;
            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);
            this.notify();
        }
    }
    
}
public class Test{
	/**
	 * 知识点:仓储模型
	 * 
	 * 注意:一个生产者一个消费者的情况
	 */
    Store store =new Store();
    Producer p=new Producer(store);
    Consumer c=new Consumer(store);
    p.start();
    c.start();
}

知识点:仓储模型
注意:多个生产者多个消费者的情况

//蛋糕类
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 + "]";
	}
	
}

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

	@Override
	public void run() {
		while(true){
			store.pop();
		}
	}
}
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);
		}
	}
}
public class Store {

	//蛋糕容器
	private LinkedList<Cake> list = new LinkedList<>();
	//最大容量
	private int maxCapacity = 20;
	//当前容量
	private int currentCapacity;
	
	
	//currentCapacity - 22
	
	//入库
	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();
		}
	}
}
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();
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

榮十一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值