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();
}
}
}
}
运行效果