Java多線程編程中生產者-消費者模式的詳解

生產者-消費者模式是一個經典的多線程設計模式,它爲多線程的協作提供了良好的解決方案。在生產者-消費者模式中,通常有兩類線程,即若干個生產者線程和若干個消費者線程。生產者線程負責提交用戶請求,消費者線程負責處理用戶請求。生產者和消費者之間通過共享內存緩衝區進行通信。

生產者-消費者模式中的內存緩衝區的主要功能是數據在多線程間的共享。此外,通過該緩衝區,可以緩解生產者和消費者之間的性能差。

Java多線程編程中,常用的多線程設計模式包括:Future模式、Master-Worker模式、Guarded Suspeionsion模式、不變模式和生產者-消費者模式等。這篇文章主要講述不變模式,關於其他多線程設計模式的地址如下:
關於Future模式的詳解: Java多線程編程中Future模式的詳解
關於Master-Worker模式的詳解: Java多線程編程中Master-Worker模式的詳解
關於Guarded Suspeionsion模式的詳解: Java多線程編程中Guarded Suspeionsion模式的詳解
關於不變模式的詳解: Java多線程編程中不變模式的詳解

下面以生產者生產饅頭、消費者吃饅頭爲例說明生產者-消費者模式,並用Java代碼實現。


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();
	}
}
運行上述結果,後臺打印如下:


全文完。轉載請註明出處。


參考文獻

1. 葛一鳴,Java程序性能優化.清華大學出版社.

2. 北京尚學堂輔導機構網絡視頻.


發佈了52 篇原創文章 · 獲贊 17 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章