在并发编程中,生产者-消费者(producer-consumer)是一个经典的问题;一个数据缓冲区,一个或多个生产者向这个缓冲区写数据,一个或多个消费者从这个缓冲区中读数据,缓冲区做为线程共享资源,须要采用同步机制控制,好比使用synchronized关键字,可是咱们还须要更多的限制条件,好比当缓冲区满时就不能在写入数据,当缓冲区空时就不能在读取数据;java
对于这种状况,Javaz提供了wait() , notify()和notifyAll() 方法,这几个方法都是Object对象的方法;一个线程只能在synchronized代码块中调用wait()方法,若是在synchronized代码块以外调用wait()方法,JVM将会抛出一个IllegalMonitorStateException异常;当一个线程调用wait()方法时,这个线程将会被休眠(sleep)而且释放对以前锁定的对象中的同步代码块,此时其它线程将有机会执行这个对象的同步代码块;当要唤醒这个线城时,能够调用被锁定对象的notify()或notifyAll()方法;编程
下面的实例中将会展现这几个方法是如何使用的;并发
1. 建立一个EventStorage类ide
public class EventStorage { private int maxSize; private LinkedList<Date> storage; public EventStorage(){ maxSize=10; storage = new LinkedList<>(); } public synchronized void set() { while (storage.size() == maxSize) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } storage.offer(new Date()); System.out.printf("Set:%d\n",storage.size()); notifyAll(); } public synchronized void get() { while (storage.size() == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.printf("Get:%d: %s\n", storage.size(), storage.poll()); notifyAll(); } }2.分别建立生产者和消费者
public class Consumer implements Runnable { private EventStorage eventStorage; public Consumer(EventStorage eventStorage) { this.eventStorage = eventStorage; } @Override public void run() { for (int i = 0; i < 100; i++) { eventStorage.get(); } } }
public class Producer implements Runnable { private EventStorage eventStorage; public Producer(EventStorage eventStorage) { this.eventStorage = eventStorage; } @Override public void run() { for (int i = 0; i < 100; i++) { eventStorage.set(); } } }
public class Main { 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(); } }