需求分析:生产者生产产品,存放在仓库里,消费者从仓库里消费产品。
程序分析:
1、生产者仅仅在仓储未满时候生产,仓满则停止生产。
2、消费者仅仅在仓储有产品时候才能消费,仓空则等待。
3、当消费者发现仓储没产品可消费时候会通知生产者生产。
4、生产者在生产出可消费产品时候,应该通知等待的消费者去消费。

package duoxiancheng;

public class ProducersAndConsumers {
	public static void main(String[] args) {
		Storage storage = new Storage();
		Thread consumer = new Thread(new Consumer(storage));
		consumer.setName("消费者");
		Thread producer = new Thread(new Producer(storage));
		producer.setName("生产者");
		consumer.start();
		producer.start();
	}
}

/**
 * 消费者
 */
class Consumer implements Runnable {
	private Storage storage;

	public Consumer(Storage storage) {
		this.storage = storage;
	}

	@Override
	public void run() {
		storage.pop();// 从仓库中取出商品
	}
}

/**
 * 生产者
 */
class Producer implements Runnable {
	private Storage storage;

	public Producer(Storage storage) {
		this.storage = storage;
	}

//手动输入商品
	@Override
	public void run() {
		Product product = new Product("0001", "手机");
		Product product2 = new Product("0002", "平板");
		storage.push(product);
		storage.push(product2);
	}

}

/**
 * 产品类
 */
class Product {
	private String id;// 产品id
	private String name;// 产品名称

	public Product(String id, String name) {
		this.id = id;
		this.name = name;
	}

	@Override
	public String toString() {
		return "(产品ID:" + id + " 产品名称:" + name + ")";
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

/**
 * 仓库
 */
class Storage {
	// 仓库容量为10
	private Product[] products = new Product[10];
	private int top = 0;

	// 生产者往仓库中放入产品,定义临界区域。同步方法机制
	public synchronized void push(Product product) {
		while (top == products.length) {
			try {
				wait();// 仓库已满,等待
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 把产品放入仓库
		products[top++] = product;
		System.out.println(Thread.currentThread().getName() + " 生产了产品" + product);
		notifyAll();// 唤醒等待线程

	}

	// 消费者从仓库中取出产品
	public synchronized Product pop() {
		while (top == 0) {
			try {
				wait();// 仓库空,等待
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		// 从仓库中取产品
		--top;
		Product p = new Product(products[top].getId(), products[top].getName());
		products[top] = null;
		System.out.println(Thread.currentThread().getName() + " 消费了产品" + p);
		notifyAll();// 唤醒等待线程
		return p;
	}
}
posted on 2022-08-28 22:20  热爱技术的小郑  阅读(29)  评论(0编辑  收藏  举报