public class Demo14 {
public static void main(String[] args) {
// 创建包子容器
ArrayList<String> list = new ArrayList<>();
new Thread(new BaoZiPu(list)).start();
new Thread(new ChiHuo(list)).start();
}
}
生产者
public class BaoZiPu implements Runnable {
private ArrayList<String> list;
public BaoZiPu(ArrayList<String> list) {
this.list = list;
}
@Override
public void run() {
System.out.println("包子铺启动了...");
int num = 1;
while (true) { // 循环来生成包子
synchronized (list) {
// 1.如果有包子就等待
if (list.size() > 0) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 2.如果没有包子就生成一个包子,通知吃货线程
String baoZi = "包子" + num;
num++;
list.add(baoZi);
System.out.println("包子铺生成一个包子: " + list);
list.notify();
}
}
}
}
消费者
public class ChiHuo implements Runnable {
private ArrayList<String> list;
public ChiHuo(ArrayList<String> list) {
this.list = list;
}
@Override
public void run() {
System.out.println("吃货启动了...");
while (true) { // 循环吃包子
synchronized (list) {
// 1.如果没有包子就等待
if (list.size() == 0) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 2.如果有包子就吃包子,通知包子铺
String baozi = list.remove(0);
System.out.println("吃货吃了一个包子: " + baozi);
list.notify();
}
}
}
}
划重点:生产者和消费者用的锁都是在main 方法中创建的list,这才可以彼此相互唤醒
有没有感觉这个跟ActiveMQ或RabbitMq的消息队列很像?但消息队列中消费者不需要通知生产者,个人觉得消息队列的设计更像观察者模式那样.
网友评论