使用阻塞缓冲区的生产者消费者
Repository
?
重点在于Repertory类的实现,该类提供阻塞的addProduct和getProduct,来达到生产者与消费者之间的协调。
?
public class Repertory {private int product = 0;public synchronized void addProduct() {if(this.product >= 5) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}else {product++;System.out.println("Producer produce the " + product + "production");this.notifyAll();}}public synchronized void getProduct() {if(this.product <= 0) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}else {System.out.println("Consumer takes the " + product + "production");product--;this.notifyAll();}}}?
?
Producer和Consumer
?
拥有Repository的一个实例。不需要考虑同步的问题。
?
public class Producer implements Runnable {private Repertory repertory;public Producer(Repertory repertory) {this.repertory = repertory;}public void run() {System.out.println("Producer begins to produce");while(true) {try {Thread.sleep((int) (Math.random() * 10) * 100);} catch (InterruptedException e) {e.printStackTrace();}repertory.addProduct();}}}public class Consumer implements Runnable {private Repertory repertory;public Consumer(Repertory repertory) {this.repertory = repertory;}public void run() {System.out.println("Consumer begin to take");while(true) {try {Thread.sleep((int) (Math.random() * 10) * 100);} catch(InterruptedException e) {e.printStackTrace();}repertory.getProduct();}}}?
?
ProductTest
?
产生两个线程用于生产者和消费者。
?
public class ProductTest {public static void main(String[] args) {Repertory repertory = new Repertory();new Thread(new Producer(repertory)).start();new Thread(new Consumer(repertory)).start();}}