[java线程同步]生产者消费者问题demo

public class ProducerAndConsumer {
	public static void main(String[] args) {
//		创建商店
		final Shop shop = new Shop(10);

//		创建消费者,并为每个消费者启动一个线程
		for (int i = 0; i < 5; i++) {
			final Consumer c = new Consumer(shop,"消费者"+i);
			new Thread(new Runnable() {

				public void run() {
//					每个消费者进行50次消费
					for (int  j = 0; j < 50; j++) {
						try {
							c.consume();
//							每次消费后随机等待一段时间
							Thread.sleep((int) Math.random() * 50);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}

//		创建生产者,并为每个生产者启动一个线程
		for (int i = 0; i < 3; i++) {
			final Producer p = new Producer(shop, "生产者"+i);
			new Thread(new Runnable() {
				
				public void run() {
//					每个生产者进行50次生产
					for (int j = 0; j < 50; j++) {
						try {
							p.produce();
//							每次生产后随机等待一段时间,
							Thread.sleep((int) Math.random() * 50);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		}
	}
}

//生产者
class Producer {
	private Shop shop;
	private String name;

	public Producer(Shop shop, String name) {
		this.shop = shop;
		this.name = name;
		System.out.println("创建生产者" + name);
	}

//	生产一件商品
	public void produce() throws Exception {
		
		/*要注意,为了与Consumer.consume()方法线程同步.
		线程锁为shop对象,而不是this,
		总结起来:如果希望几个方法(或代码段)线程同步,那么作为线程锁的对象必须为同一个*/
		synchronized (shop) {
//			商品数量达到商店最大容量时,释放当前线程的锁,并等待
			if (shop.getProductNum() >= shop.getCapacity()) {
				System.out.println("仓库已满,等待消费");
				shop.wait();
			} else {
				System.out.println(name + "生产了一件商品");
				shop.setProductNum(shop.getProductNum() + 1);
				shop.notifyAll();
			}
		}
	}
}

//消费者
class Consumer {
	private Shop shop;
	private String name;

	public Consumer(Shop shop, String name) {
		this.shop = shop;
		this.name = name;
		System.out.println("创建消费者" + name);
	}

//	消费一件商品
	public void consume() throws Exception {
		
		synchronized (shop) {
			if (shop.getProductNum() == 0) {
				System.out.println("仓库已空,等待生产");
				shop.wait();
			} else {
				System.out.println(name + "消费一件商品");
				shop.setProductNum(shop.getProductNum() - 1);
				shop.notifyAll();
			}
		}
	}
}

//商店
class Shop {
//	当前商品数量
	private int productNum = 0;
	
//	最大商品容量
	private int capacity;

	public Shop(int capacity) {
		this.capacity = capacity;
		System.out.println("创建商店");
	}

	public int getProductNum() {
		return productNum;
	}

	public void setProductNum(int productNum) {
		this.productNum = productNum;
		System.out.println("产品数量:" + productNum);
	}

	public int getCapacity() {
		return capacity;
	}

	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值