Java生产者消费者简易版

一、模拟仓库

package 生产者消费者;

import java.util.LinkedList;

/*
 * 1.模拟仓库类
 * */
public class Storage {

	// 定义最大存储量
	private final int MAX_SIZE = 100;

	// 定义列表存储商品
	private LinkedList<Object> list = new LinkedList<Object>();

	// 生产num个商品
	synchronized public void produce(int num) {

		while (list.size() + num > MAX_SIZE) {

			System.out.println("【要生产的产品数】:" + num + "\t库存量:" + list.size()
					+ "暂时不能执行生产任务 ");
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		for (int i = 1; i <= num; i++) {
			list.add(new Object());
		}
		System.out.println("【已经生产产品数】:" + num + "\t【现仓储为】:" + list.size());
		this.notifyAll();

	}

	// 消费num个商品
	synchronized public void consumer(int num) {

		while (list.size() < num) {

			System.out.println("【要消费的产品数量】:" + num + "\t【库存量】:" + list.size()
					+ "\t暂时不能执行消费任务!");
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		for (int i = 1; i <= num; i++) {
			list.remove();
		}

		System.out.println("【已经消费产品数】:" + num + "\t【现仓储量为】:" + list.size());
		this.notifyAll();

	}
}


二、模拟生产者

package 生产者消费者;

public class Producer extends Thread {

	private Storage storage;
	private int num;

	public Producer(Storage storage, int num) {
		super();
		this.storage = storage;
		this.num = num;
	}

	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			storage.produce(num);
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}

	}

}


三、模拟消费者

package 生产者消费者;

public class Consumer extends Thread {
	private Storage storage;
	private int num;

	public Consumer(Storage storage, int num) {
		super();
		this.storage = storage;
		this.num = num;
	}

	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {
			storage.consumer(num);
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}
	}

}


四、测试

package 生产者消费者;

public class Test {

	public static void main(String[] args) {
		Storage storage = new Storage();
		Producer p1 = new Producer(storage, 2);
		Producer p2 = new Producer(storage, 4);
		Producer p3 = new Producer(storage, 6);
		Producer p4 = new Producer(storage, 8);
		Producer p5 = new Producer(storage, 10);

		Consumer c1 = new Consumer(storage, 1);
		Consumer c2 = new Consumer(storage, 3);
		Consumer c3 = new Consumer(storage, 5);
		Consumer c4 = new Consumer(storage, 7);
		Consumer c5 = new Consumer(storage, 9);

		p1.start();
		p2.start();
		p3.start();
		p4.start();
		p5.start();

		c1.start();
		c2.start();
		c3.start();
		c4.start();
		c5.start();

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值