生产者消费者模式

package com.ck.Threads;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 生产者消费者模式
 * 
 * @author sansheng__
 *
 */
public class ConsumerAndProducer {

	public static void main(String[] args) {
                //食物队列
		Queue<Food> queue = new LinkedList<Food>();
		int maxSize = 10;

		Producer producer = new Producer(queue, maxSize,"李大嘴");
		Consumer consumer1 = new Consumer(queue,"白展堂");
		Consumer consumer2 = new Consumer(queue,"佟湘玉");
		Consumer consumer3 = new Consumer(queue,"郭芙蓉");

		producer.start();
		consumer1.start();
		consumer2.start();
		consumer3.start();
	}

}

/**
 * 生产者
 */
class Producer extends Thread {
	private Queue<Food> queue;
	private int maxSize;
	private String name;

	public Producer() {
		super();
	}

	public Producer(Queue<Food> queue, int maxSize, String name) {
		super();
		this.queue = queue;
		this.maxSize = maxSize;
		this.name = name;
	}


	@Override
	public void run() {
		this.setName(this.name);
		while (true) {
			// 将食物队列锁住
			synchronized (queue) {
				// 模拟网络时延
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				// 当食物队列满了,停止生产食物
				while (queue.size() == maxSize) {
					try {
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Food food = new Food("包子");
				queue.add(food);
				System.out.println(this.getName() + "生产食物:" + food.getName());
				// 唤醒消费者
				queue.notifyAll();
			}
		}
	}

}

/**
 * 消费者
 */
class Consumer extends Thread {
	private Queue<Food> queue;
	private String name;
	
	public Consumer() {
		super();
	}

	public Consumer(Queue<Food> queue, String name) {
		super();
		this.queue = queue;
		this.name = name;
	}



	@Override
	public void run() {
		this.setName(this.name);
		while (true) {
			// 将食物队列锁住
			synchronized (queue) {
				// 模拟网络时延
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 当食物队列空了,停止消费食物
				//这里一定要用while,因为当生产者生产食物后,会唤醒所有消费者,如果是if的话,被唤醒的消费者不会再去判断食物队列是否为空就会出现错误,
				//while会让消费者重新判断食物是否为空,再去执行是消费食物还是继续等待
				while (queue.isEmpty()) {
					try {
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Food food = queue.poll();
				System.out.println(this.getName() + "消费食物:" + food.getName());
				// 唤醒提供者
				queue.notifyAll();
			}
		}
	}

}

运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值