生產者-消費者(producer-consumer)問題是一個著名的進程同步問題。它描述的是:有一個生產者進程在生產產品,並將這些產品提供給消費者進程去消費。為使生產者進程與消費者進程並發執行,在兩者之間設定了一個具有n個緩衝池,生產者進程將它所生產的產品放入一個緩衝區中;消費者進程從一個緩衝區中取走產品去消費。儘管所有的生產者進程和消費者進程都是非同步方式啟動並執行,但它們之間必須保持同步,既不允許消費者進程到一個空緩衝區去取東西,也不允許生產者進程向一個已裝滿產品並且未被取走的緩衝區中投放產品。
視頻中的例子,在這裡記錄下來:
public class ProducerConsumer{public static void main(String[] args){Basket basket = new Basket();Producer pp = new Producer(basket);Consumer cc = new Consumer(basket);new Thread(pp).start();new Thread(cc).start();}}//食物類class Foods{int id;Foods(int id){this.id = id;}//重寫toString方法public String toString(){return "Foods : " + id;}}//放食物的籃子類class Basket{int num = 0;Foods[] arrFood = new Foods[10];public synchronized void push(Foods f){while(num == arrFood.length){try{this.wait();}catch(InterruptedException e){e.printStackTrace();}}this.notify();arrFood[num] = f;num++;}public synchronized Foods pop(){while(num == 0){try{this.wait();}catch(InterruptedException e){e.printStackTrace();}}this.notify();num--;return arrFood[num];}}//生產者類class Producer implements Runnable{Basket basket = null;Producer(Basket basket){this.basket = basket;}public void run(){for(int i = 0; i < 20; i++){Foods f = new Foods(i);basket.push(f);System.out.println("生產了: " + f);try{Thread.sleep((int)(Math.random() * 1000));}catch(InterruptedException e){e.printStackTrace();}}}}//消費者類class Consumer implements Runnable{Basket basket = null;Consumer(Basket basket){this.basket = basket;}public void run(){for(int i = 0; i < 20; i++){Foods f = basket.pop();System.out.println("消費了: " + f);try{Thread.sleep((int)(Math.random() * 1000));}catch(InterruptedException e){e.printStackTrace();}}}}