Java多线程之~~~~使用wait和notify实现生产者消费者模型

来源:互联网 发布:软件开发人员保密协议 编辑:程序博客网 时间:2024/05/17 23:08

在多线程开发中,最经典的一个模型就是生产者消费者模型,他们有一个缓冲区,缓冲区有最大限制,当缓冲区满
的时候,生产者是不能将产品放入到缓冲区里面的,当然,当缓冲区是空的时候,消费者也不能从中拿出来产品,这就
涉及到了在多线程中的条件判断,Java为了实现这些功能,提供了wait和notify方法,他们可以在线程不满足要求的时候
让线程让出来资源等待,当有资源的时候再notify他们让他们继续工作,下面我们用实际的代码来展示如何使用wait和
notify来实现生产者消费者这个经典的模型。

首先是缓冲区的实现,我们使用LinkedList来代替

[java] view plain copy print?
package com.bird.concursey.charpet2;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class EventStorage {

private int maxSize;  private List<Date> storage;  public EventStorage() {      maxSize = 10;      storage = new LinkedList<Date>();  }  public synchronized void set() {      while(storage.size() == maxSize) {          try {              wait();          } catch (InterruptedException e) {              e.printStackTrace();          }      }      storage.add(new Date());      System.out.printf("Set: %d",storage.size());      notifyAll();  }  public synchronized void get() {      while(storage.size() == 0) {          try {              wait();          } catch (InterruptedException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }      }      System.out.printf("Get: %d: %s",storage.size(),((LinkedList<?>)storage).poll());      notifyAll();  }  

}

然后就是生产者和消费者

[java] view plain copy print?
package com.bird.concursey.charpet2;

public class Producer implements Runnable {

private EventStorage storge;  public Producer(EventStorage storage) {      this.storge = storage;  }  @Override  public void run() {      for(int i = 0; i < 100; i++) {          storge.set();      }  }  

}

[java] view plain copy print?
package com.bird.concursey.charpet2;

public class Consumer implements Runnable {

private EventStorage storage;  public Consumer(EventStorage storage) {      this.storage = storage;  }  @Override  public void run() {      for(int i = 0; i < 100; i++) {          storage.get();      }  }  public static void main(String[] args) {      EventStorage storage = new EventStorage();      Producer producer = new Producer(storage);      Thread thread1 = new Thread(producer);      Consumer consumer = new Consumer(storage);      Thread thread2 = new Thread(consumer);      thread2.start();      thread1.start();  }  

}

可以看到,这里面就是用了wait和notifyall方法实现了生产者消费方法,具体的运行过程大家可以通过阅读代码来体
会,还是很直观的。

0 0
原创粉丝点击