多线程编程中的一个典型问题是生产者与消费者问题,这是线程同步或者说是线程间通信的一个典型实例。这里再简单复习一下吧。
在这个问题中,有一个生产者负责源源不断地生成产品放入仓库,还一个消费者源源不断地从仓库中提出产品。仓库有一个固定的容量,仓库满的时候生产者的操作要暂时挂起等待仓库有空间时再放入产品,当仓库空的时候,消费者提取产品的工作也会挂起,等待仓库中有产品放入后再继续。因此说,存放产品和提取产品是两个需要同步的操作,或者准确地说:消费者的消费操作和生产者的生产操作是可以同步进行的(并发执行),但同时它们之间又必须通过一定的机制来相互的协调,在某些特殊的时刻,让谁先执行,谁后执行,才能避免出现上述问题。
在java中,这个问题就是通过wait和notify来实现的。注意:wait和notify必须放在同步块中!一般情况是同步块的加锁对象就是wait和notify的从属对象。wait方法将释放当前对象的锁,这样当前线程就被置于block状态(因为当前线程在当前对象上是同步的),以便其他线程可以执行,直到它需要的某个条件由其他线程实现了。而notify方法正是那个实现了某个条件的线程用来通知虚拟机,可以尝试唤醒其他线程了。等到这个线程执行完毕,归还了当前对象的锁,某个被唤醒的线程会得到这个锁,比如说前一个wait的线程,这时候它们条件已经满足,因而可以继续执行下去了。
wait和notify与同步机制的关系: “竞争条件”是指两个以上的线程会因为执行顺序的不同而导致程序变量或是返回值的不同。这样必然会出现错误的结果,这种错误的结果有一种叫法:共享数据的腐蚀。同步机制正是用来解决“竞争条件”问题的。但是仅有同步是不够的,本质上,同步是确保共享数据能被线程安全地访问, 它是从“ 隔离 线程”角度来安排线程的推进的。但是线程除了需要隔离,还需要相互通信,以协调地完成一项工作,这正是wait和notify的作用。以下是Java Theads一书的摘入:
The wait-and-notify mechanism is a synchronization mechanism. However, it is more of a communication mechanism: it allows one thread to communicate to another thread that a particular condition has occurred. The wait-and-notify mechanism does not specify what the specific condition is.
Can the wait-and-notify mechanism be used to replace the synchronized mechanism? Actually, the answer is no; wait-and-notify does not solve the race condition problem that the synchronized mechanism solves. As a matter of fact, wait-and-notify must be used in conjunction with the synchronized lock to prevent a race condition in the wait-and-notify mechanism itself.
下面是生产者与消费者的代码:
Store:仓库类
package producer; import java.util.LinkedList; import java.util.Queue; public class Store { private Queue<String> queue = new LinkedList<String>(); public synchronized String get() { try { System.out.println("Start to get..."); System.out.println("The store's size is " + queue.size()); //NOTE: Here is while NOT if. If there are two consumers, //When a producer set a product to this store, and notified other //threads, one of those two consumers will get lock and go on get production, //but there is a notification too in get method, it may await the other consumer, //that consumer try to get product, however, there's no product at that time! //So, we have to let program check again! while (queue.isEmpty()) { System.out.println("waiting get..."); wait(); } System.out.println("The store's size is " + queue.size()); String product = queue.remove(); System.out.println("End to get..."); notify(); return product; } catch (InterruptedException e) { e.printStackTrace(); return null; } } public synchronized void set(String product) { try { System.out.println("Start to set..."); System.out.println("The store's size is " + queue.size()); while (queue.size() == 3) { System.out.println("waiting set..."); wait(); } System.out.println("The store's size is " + queue.size()); queue.add(product); System.out.println("End to set..."); notify(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Store s = new Store(); Consumer c1 = new Consumer(s); Producer p1 = new Producer(s); Consumer c2 = new Consumer(s); Producer p2 = new Producer(s); Thread t1 = new Thread(c1); Thread t2 = new Thread(p1); Thread t3 = new Thread(c2); Thread t4 = new Thread(p2); t1.start(); t2.start(); t3.start(); t4.start(); } }
Producer:生产者
package producer; import java.util.Random; public class Producer implements Runnable { private Store store; public Producer(Store store) { super(); this.store = store; } @Override public void run() { try { while(true){ store.set("a"); System.out.println(); Thread.sleep(new Random().nextInt(1000)); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Consumer:消费者
package producer; import java.util.Random; public class Consumer implements Runnable{ private Store store; public Consumer(Store store) { super(); this.store = store; } @Override public void run() { try { while(true){ Thread.sleep(new Random().nextInt(1000)); System.out.println(store.get()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }