Java中的生产消费者问题

时间:2023-03-09 15:13:11
Java中的生产消费者问题
 package day190109;

 import java.util.LinkedList;
import java.util.Queue;
import java.util.Random; public class 生产消费者ThreadDemo10 {
public static void main(String[] args) {
//生产消费者模式
Queue<Phone> queue = new LinkedList<Phone>();
Producer producer = new Producer(queue,30);
Consumers consumers = new Consumers(queue,"李江萍");
Consumers consumers1 = new Consumers(queue,"熊天明"); producer.start();
consumers.start();
consumers1.start(); }
}
class Producer extends Thread{
public Queue<Phone> queue;
public int max;
//构造方法
public Producer(Queue<Phone> queue, int max) {
this.queue = queue;
this.max = max;
} @Override
public void run() {
while (true){
synchronized (queue) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (queue.size() == max) { //如果生产的商品满啦
try {
System.out.println("你好!本地库存产品已满!请通知消费之前来消费");
queue.wait();//先不忙生产,让消费者先消费
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Random r = new Random();
Phone p = new Phone(r.nextInt(7), (double) r.nextInt(2000));
System.out.println("甲方已经生产了1个手机:" + p);
queue.offer(p);
System.out.println(" 生产后现在的库存是:" + queue.size()+"个");
queue.notifyAll();//通知消费者。可以消费啦
}
}
}
}
}
class Consumers extends Thread{
public Queue<Phone> queue;
public String name;
//构造方法
public Consumers(Queue<Phone> queue, String name) {
this.queue = queue;
this.name = name;
} @Override
public void run() {
while (true) {
synchronized (queue) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (queue.size() == 0) {
try {
System.out.println(this.name+"说:“你们本地库存产品严重不足”");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Phone p = queue.poll();
System.out.println(this.name + "说:我要买1个手机:" + p);
System.out.println(" 消费后现在的库存是:" + queue.size()+"个");
queue.notifyAll();//通知生产者可以生产了
}
}
}
}
}
class Phone{
private Integer size;
private Double price; public Phone(Integer size, Double price) {
this.size = size;
this.price = price; } @Override
public String toString() {
return "手机规格是{" +
"尺寸是:" + size +
", 价格是:" + price +"元"+
'}';
}
}