简单的生产者与消费者实现
同步堆栈,用于存储。
public class SyncStack {private int index = 0;private char[] data = new char[6];public synchronized void push(char c){while(index == data.length){try{this.wait();}catch(InterruptedException e){}}this.notify();data[index] = c;index ++;System.out.println("Produced:" + c);}public synchronized char pop(){while(index == 0){try{this.wait();}catch(InterruptedException e){}}this.notify();index--;System.out.println("Consume:" + data[index]);return data[index];}}
生产者线程:
public class Producer implements Runnable{SyncStack stack;public Producer(SyncStack stack){this.stack = stack;}public void run(){for(int i=0; i<20; i++){char c = (char)(Math.random()*26 + 'A');stack.push(c);try{Thread.sleep((int)Math.random()*300);}catch(InterruptedException e){e.printStackTrace();}}}}
?消费者线程:
public class Consumer implements Runnable{private SyncStack stack;public Consumer(SyncStack stack){this.stack = stack;}public void run(){for(int i=0; i<20; i++){char c = stack.pop();try{Thread.sleep((int)Math.random()*300);}catch(InterruptedException e){e.printStackTrace();}}}}
??? 测试:
public class SyncTest {public static void main(String args[]){SyncStack stack = new SyncStack();Runnable p = new Producer(stack);Runnable c = new Consumer(stack);Thread t1 = new Thread(p);Thread t2 = new Thread(c);t1.start();t2.start();}}?
wait()?和?notify()?方法的特性决定了它们经常和synchronized?方法或块一起使用,将它们和操作系统的进程间通信机制作一个比较就会发现它们的相似性:synchronized方法或块提供了类似于操作系统原语的功能,它们的执行不会受到多线程机制的干扰,而这一对方法则相当于?block?和wakeup?原语(这一对方法均声明为?synchronized)。它们的结合使得我们可以实现操作系统上一系列精妙的进程间通信的算法(如信号量算法),并用于解决各种复杂的线程间通信问题。
关于?wait()?和?notify()?方法最后再说明两点:
???第一:调用?notify()?方法导致解除阻塞的线程是从因调用该对象的?wait()?方法而阻塞的线程中随机选取的,我们无法预料哪一个线程将会被选择,所以编程时要特别小心,避免因这种不确定性而产生问题。
???第二:除了?notify(),还有一个方法?notifyAll()?也可起到类似作用,唯一的区别在于,调用?notifyAll()?方法将把因调用该对象的?wait()?方法而阻塞的所有线程一次性全部解除阻塞。当然,只有获得锁的那一个线程才能进入可执行状态。