生产者消费者模式并不是GOF提出的23中设计模式之一,23中设计模式都是建立在面向对象的基础之上的,但其实面向过程的编程中也有很多高效的编程模式,生产者消费者模式便是其中之一,它是编程中常用的一种设计模式.
生产者消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一存储空间,生产者产生数据,消费者取出数据
代码:
生产者
// 生产者
public class Demo9_producer implements Runnable {
Demo9_clerk clerk;
public Demo9_producer(Demo9_clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
while(true)
this.clerk.producerCommodity();
}
}
消费者
// 消费者
public class Demo9_consumer implements Runnable {
Demo9_clerk clerk;
public Demo9_consumer(Demo9_clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
while(true)
this.clerk.consumerCommodity();
}
}
public class Demo9_clerk {
int commodity = 10;
// 卖商品
public synchronized void producerCommodity() {
notifyAll();
if(commodity>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
commodity--;
System.out.println(Thread.currentThread().getName()+"卖1件商品,还剩"+commodity+"商品");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 进商品
public synchronized void consumerCommodity() {
notifyAll();
if(commodity<10) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
commodity++;
System.out.println(Thread.currentThread().getName()+"进1件商品,还剩"+commodity+"商品");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Demo9_test {
public static void main(String[] args) {
Demo9_clerk clerk = new Demo9_clerk();
Demo9_producer producer = new Demo9_producer(clerk);
Demo9_consumer consumer = new Demo9_consumer(clerk);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
Thread t3 = new Thread(producer);
t1.start();
t2.start();
t3.start();
}
}
网友评论