本文共 1316 字,大约阅读时间需要 4 分钟。
//生产者——消费者 通用模式
// 1、while()
// 2、notifyAll()
//理解思路:
// 1、标记flag,理解为仓库里有产品。则不再生产改变标记,在不再生产前唤醒消费线程们。
// 2、生产的线程则因为循环,执行等待。
// 3、等待的线程被唤醒后,第一件事是重新判断标记,是否仓库有货,即while循环的条件判断,如没货才可以生产,有货则消费。
class Resource {
private String name;
private int count = 0;
private boolean flag = false;
public synchronized void produce(String name) {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name + (++count);
System.out.println("生产:" + this.name);
flag = !flag;
notifyAll();
}
public synchronized void consume() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("...........消费:" + name);
flag = !flag;
notifyAll();
}
}
class Producer implements Runnable {
private Resource r;
public Producer(Resource r) {
this.r = r;
}
public void run() {
while (true) {
r.produce("商品");
}
}
}
class Consumer implements Runnable {
private Resource r;
public Consumer(Resource r) {
this.r = r;
}
public void run() {
while (true) {
r.consume();
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
//多个生产者消费者时:
new Thread(pro).start();
new Thread(pro).start();
new Thread(con).start();
new Thread(con).start();
}
}
转载地址:https://blog.csdn.net/weixin_35600779/article/details/114390488 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!