生产者和消费者问题

public class ComsumerAndProducer {
	public static void main(String[] args) {
		LanZhi lz = new LanZhi();

		// 用同一个篮子初始化生产者和消费者,使生产者和消费者竞争同一个对象锁
		Comsumer comsumer = new Comsumer(lz);
		Producer producer = new Producer(lz);

		// 同一个comsumer起三个线程,一共可以消费60个馒头
		new Thread(comsumer, "comsumer1").start();
		new Thread(comsumer, "comsumer2").start();
		new Thread(comsumer, "comsumer3").start();

		// 一个生产者可以生产60个馒头
		new Thread(producer, "producer").start();
	}
}

class ManTou {
	private int id; // 馒头的id

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

	public int getId() {
		return id;
	}

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

class LanZhi {
	ManTou[] manTous = new ManTou[6];
	int index = 0;

	public synchronized void put(ManTou mt) {
		// 注意这里一定是while,否则不会连续阻塞
		while (index == manTous.length) {
			try {
				System.out.println("put wait:"
						+ Thread.currentThread().getName());
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		manTous[index] = mt;
		System.out.println(Thread.currentThread().getName() + " put a man tou "
				+ mt.getId());
		index++;
		notify();
	}

	public synchronized ManTou get() {
		while (index == 0) {
			try {
				System.out.println("get wait: "
						+ Thread.currentThread().getName());
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		index--;
		ManTou mt = manTous[index];
		System.out.println(Thread.currentThread().getName() + " get a man tou "
				+ mt.getId());
		notify();
		return mt;
	}
}

class Comsumer implements Runnable {
	LanZhi lz = null;

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			lz.get();
			try {
				// 取一个馒头后,休息个随机事件
				Thread.sleep((int) (Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public Comsumer(LanZhi lz) {
		this.lz = lz;
	}
}

class Producer implements Runnable {
	LanZhi lz = null;

	@Override
	public void run() {
		for (int i = 0; i < 60; i++) {
			ManTou mt = new ManTou(i);
			lz.put(mt);
			try {
				// 放一个馒头后休息随机时间
				Thread.sleep((int) Math.random() * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public Producer(LanZhi lz) {
		this.lz = lz;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值