管程法实现生产者消费者模式

package monitormethod;

/**
 * 
 * @author 丢了风筝的线
 * @see 测试管程法
 */
public class Test {
	public static void main(String[] args) {
		Warehouse warehouse = new Warehouse();
		new Producer(warehouse).start();
		new Consumer(warehouse).start();

	}
}

package monitormethod;

/**
 * 
 * @author 丢了风筝的线
 * @see 存放商品的仓库
 */
public class Warehouse {

	// 存放产品的容器
	Producets[] producets = new Producets[10];

	// 产品的个数
	int count = 0;

	// 存放 生产
	public synchronized void push(Producets ps) {

		// 判断何时等待消费
		if (count == producets.length) {
			try {
				this.wait(); // 当生产者通知可以生产的时候才解除
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		producets[count++] = ps;

		// 有了产品之后就通知消费
		this.notifyAll();
	}

	// 获取 消费
	public synchronized Producets pop() {

		// 判断何时等待生产
		if (count == 0) {
			try {
				this.wait();// 当生产者通知可以消费时才解除
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}
		count--;

		// 一旦消费有了空闲之后就可以通知生产了
		this.notifyAll();
		return producets[count];
	}

}

package monitormethod;

/**
 * 
 * @author 丢了风筝的线
 * @see 产品
 */
public class Producets {

	// 每个产品的编号
	private int id;

	public Producets(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}

package monitormethod;

/**
 * 
 * @author 丢了风筝的线
 * @see 生产者
 */
public class Producer extends Thread {
	Warehouse warehous;

	public Producer(Warehouse warehouse) {
		this.warehous = warehouse;
	}

	@Override
	public void run() {

		// 生产
		for (int i = 0; i < 100; i++) {
			System.out.println("生产第 " + i + " 个产品");
			warehous.push(new Producets(i));
		}
	}
}


package monitormethod;

/**
 * 
 * @author 丢了风筝的线
 * @see 消费者
 */
public class Consumer extends Thread {

	Warehouse warehous;

	public Consumer(Warehouse warehouse) {
		this.warehous = warehouse;
	}

	@Override
	public void run() {

		// 消费
		for (int i = 0; i < 100; i++) {
			System.out.println("消费第 " + warehous.pop().getId() + " 个元素");

		}
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值