生产者消费者模式java代码实现和理解

package com.test;

/**
 * 生产者-消费者,使用java代码实现效果
 * 定义:生产者(Producer)生产商品给仓库(Warehouse),消费者(Consumer)消费商品,仓库最多放20个商品
 * 1、存在共享数据,商品的数量(线程同步)
 * 2、生产者和消费者之前的通信(线程通信)
 * @author CCQ
 *
 */
public class ProducerAndConsumer {
	public static void main(String[] args) {
		Warehouse warehouse = new Warehouse();
		Producer p1 = new Producer(warehouse);
		Consumer c1 = new Consumer(warehouse);
		
		Thread pt1 = new Thread(p1);
		pt1.setName("生产者1");
		Thread pt2 = new Thread(p1);
		pt2.setName("生产者2");
		Thread ct1 = new Thread(c1);
		ct1.setName("消费者1");
		
		pt1.start();
		pt2.start();
		ct1.start();
	}
}

// 生产者
class Producer implements Runnable{
	
	Warehouse warehouse;
	
	public Producer(Warehouse warehouse) {
		this.warehouse = warehouse;
	}

	@Override
	public void run() {
		// 生产者在不停的生产商品
		while(true) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			warehouse.add();
		}
	}
}
// 消费者
class Consumer implements Runnable{
	
	Warehouse warehouse;
	
	public Consumer(Warehouse warehouse) {
		this.warehouse = warehouse;
	}
	
	@Override
	public void run() {
		// 消费者在不同消费商品
		while(true) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			warehouse.reduce();
		}
	}
}
// 仓库
class Warehouse{
	private int product;
	
	// 添加商品方法 原子操作 P
	public synchronized void add() {
		if(product >= 20) {
			try {
				wait();//释放cpu资源,进入等待状态
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			product++;
			System.out.println(Thread.currentThread().getName()+ "生产了第" + product + "个商品");
			notifyAll();//唤醒所有的等待的线程
		}
	}
	
	// 减少商品方法 原子操作 V
	public synchronized void reduce(){
		if(product <= 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			System.out.println(Thread.currentThread().getName()+ "消费了第" + product + "个商品");
			product--;
			notifyAll();
		}
	}
}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值