物件導向寫生產者與消費者的例子(java)

來源:互聯網
上載者:User

       生產者-消費者(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();}}}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.