class MianBao {
public String name;
public int id = 1;
MianBao(String name, int id) {
this.name = name;
this.id = id;
}
boolean flag = false;
synchronized void shengChan() {
if (flag)
try {
wait();
id++;
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...生产..." + name + id);
flag = true;
notify();
}
synchronized void mai() {
if (!flag)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-----------消费---------" + name + id);
flag = false;
notify();
}
}
class producer implements Runnable { // 定义生产者
private MianBao mianbao;
producer(MianBao mianbao) {
this.mianbao = mianbao;
}
public void run() {
while (true) {
mianbao.shengChan();
}
}
}
class consumer implements Runnable { // 定义消费者
private MianBao mianbao;
consumer(MianBao mianbao) {
this.mianbao = mianbao;
}
public void run() {
while (true) {
mianbao.mai();
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MianBao mianbao = new MianBao("面包", 1);
producer pro = new producer(mianbao);
consumer con = new consumer(mianbao);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}
}
生产者消费者模式
最新推荐文章于 2022-10-22 20:23:32 发布