在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢
,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解
决这个问题于是引入了生产者和消费者模式。
生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所
以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲
区,平衡了生产者和消费者的处理能力。(节选自http://www.infoq.com/cn/articles/producers-and-consumers-mode/)
博主新手上路,根据理解写了一个简单的生产者消费者模式,希望大神们多多指教
首先要有1种资源——馒头,馒头只有一个属性,名字
public class ManTou {
char name;
public ManTou(char name) {
this.name = name;
}
}
然后要有1个容器放馒头,就来一张桌子吧,桌子提供两个功能,放入(push)馒头和拿走(pop)馒头
public class ZhuoZi {
List<ManTou> list = new ArrayList<ManTou>();
final int s =20;
public synchronized void push(ManTou m){
try {
while(list.size()>=s){
System.out.println("桌子满了");
this.wait();
}
this.notify();
} catch (Exception e) {
}
list.add(m);
System.out.println("生产了馒头:"+m.name+",现在还有"+list.size()+"个馒头");
}
public synchronized void pop(){
try {
while(list.size()==0){
System.out.println("馒头吃光了");
this.wait();
}
this.notify();
} catch (Exception e) {
}
ManTou m = list.remove(list.size()-1);
System.out.println("吃掉了馒头"+m.name+",现在还剩"+list.size()+"个馒头");
}
}
接着是吃馒头的人(消费者)
public class Customer implements Runnable{
ZhuoZi z = new ZhuoZi();
public Customer(ZhuoZi z) {
this.z = z;
}
@Override
public void run() {
while(true) {
z.pop();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
当然也要有人生产馒头,来一个厨师(生产者)
public class producer implements Runnable{
ZhuoZi z = new ZhuoZi();
public producer(ZhuoZi z) {
this.z = z ;
}
@Override
public void run() {
while(true){
String chars = "abcdefghijklmnopqrstuvwxyz";
ManTou m = new ManTou(chars.charAt((int)(Math.random() * 26)));
z.push(m);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最后,让他们跑起来吧
public class test {
public static void main(String[] args) {
ZhuoZi z = new ZhuoZi();
Customer c = new Customer(z);
producer p = new producer(z);
Thread t1 = new Thread(c);
Thread t2 = new Thread(p);
t1.start();
t2.start();
}
}