生產者消費者簡單實現(轉載)
阿新 • • 發佈:2017-09-16
通知 用戶 好的 log zed java 數據 sleep 經典的
生產者-消費者模式是一個經典的多線程設計模式,它為多線程的協作提供了良好的解決方案。在生產者-消費者模式中,通常有兩類線程,即若幹個生產者線程和若幹個消費者線程。生產者線程負責提交用戶請求,消費者線程負責處理用戶請求。生產者和消費者之間通過共享內存緩沖區進行通信。
生產者-消費者模式中的內存緩沖區的主要功能是數據在多線程間的共享。此外,通過該緩沖區,可以緩解生產者和消費者之間的性能差。
1. 饅頭
這裏采用了面向對象的設計思想,饅頭在整個程序中自然是一個類,其Java代碼如下。
class ManTou { int id; ManTou(int id) { this.id = id; } public String toString() { return "ManTou: " + id; } }
2. 籃子(裝饅頭)
籃子是有容量的,因此籃子類需要有一個變量表示容量;籃子至少還有取和裝饅頭這兩個功能,其Java代碼如下:
class SyncStack { //籃子 int index = 0; ManTou[] arrMT = new ManTou[6]; //假設這個籃子只能裝6個饅頭 public synchronized void push(ManTou wt) { //裝饅頭while(index == arrMT.length) { //籃子滿了 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); //如果取饅頭的wait了,則通知他醒來 arrMT[index] = wt; index ++; }public synchronized ManTou pop() { //取饅頭 while(index == 0) { //籃子空了 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); //如果產饅頭的wait了,則通知他醒來 index --; return arrMT[index]; } }
3. 生產者(生產饅頭)
生產者需要獲取籃子這個對象,而且籃子不能是自己創建的。其Java代碼如下:
class Producer implements Runnable { //生產者 SyncStack ss = null; Producer(SyncStack ss) { this.ss = ss; } public void run() { for(int i=0; i<20; i++) { //一共要生成20個 ManTou wt = new ManTou(i); ss.push(wt); System.out.println("生產了:" + wt); try { //生成一個睡1秒,便於觀察 Thread.sleep((long) (Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
4. 消費者(吃饅頭)
消費需要獲取籃子這個對象,而且這個對象必須與生產者獲取的籃子是同一個對象,這樣才能信息共享。其Java代碼如下:
class Consumer implements Runnable { SyncStack ss = null; Consumer(SyncStack ss) { this.ss = ss; } public void run() { for(int i=0; i<20; i++) { //一共要吃20個 ManTou wt = ss.pop(); System.out.println("消費了:" + wt); } } }
5. 測試運行
主函數Java代碼如下:
public class ProducerConsumer { public static void main(String[] args) { SyncStack ss = new SyncStack(); //定義籃子 Producer p = new Producer(ss); //定義生產者 Consumer c = new Consumer(ss); //定義消費者 new Thread(p).start(); new Thread(c).start(); } }
轉載地址:http://blog.csdn.net/ghuil/article/details/41044257
生產者消費者簡單實現(轉載)