
生产者消费者模式是并发、多线程编程中经典的设计模式,生产者和消费者通过分离的执行工作解耦,简化了开发模式,生产者和消费者可以以不同的速度生产和消费数据。
package a;
import java.util.Random;
class Goods{
public String name;
public int price;
@Override
public String toString() {
return name+":"+price;
}
}
class Hamburger extends Goods{
public Hamburger(String name,int price) {
this.price=price;
this.name=name;
}
}
class Pizza extends Goods{
public Pizza(String name,int price) {
this.price=price;
this.name=name;
}
}
/**
* 相当于一个生产机器(生产和消费交替执行)
*/
class Model{
private Goods g;
public synchronized Goods make() throws InterruptedException {
if(g!=null) {
this.wait();
}
if(new Random().nextInt(100)%2==0) {
g=new Hamburger("汉堡",100);
}else {
g=new Pizza("披萨",200);
}
System.out.println("生产-->"+g);
this.notify();
return g;
}
public synchronized Goods buy() throws InterruptedException {
if(g==null) {
this.wait();
}
Goods gl=g;
System.out.println("消费-->"+g);
g=null;
this.notify();
return gl;
}
}
/**
* 生产者
*/
class Producer extends Thread{
public Producer(Model m) {
this.m=m;
}
private Model m;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++) {
try {
m.make();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 消费者
*/
class Consumer extends Thread{
public Consumer(Model m) {
this.m=m;
}
private Model m;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++) {
try {
m.buy();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class A5 {
public static void main(String[] args) {
Model m=new Model();
Producer p=new Producer(m);
p.start();
Consumer c=new Consumer(m);
c.start();
}
}