Producer-Consumer模式

一、定義
Producer-Consumer Pattern就是生產(chǎn)者-消費者模式聪姿。
生產(chǎn)者和消費者在為不同的處理線程咳燕,生產(chǎn)者必須將數(shù)據(jù)安全地交給消費者,消費者進(jìn)行消費時招盲,如果生產(chǎn)者還沒有建立數(shù)據(jù)曹货,則消費者需要等待。
一般來說玩般,可能存在多個生產(chǎn)者和消費者礼饱,不過也有可能生產(chǎn)者和消費者都只有一個,當(dāng)雙方都只有一個時匀伏,我們也稱之為Pipe Pattern蝴韭。

二榄鉴、模式案例
該案例中蛉抓,定義了3個角色:廚師、客人剃诅、桌子巷送。

廚師(生產(chǎn)者)定義:

public class MakerThread extends Thread {
    private final Random random;
    private final Table table;
    private static int id = 0;     //蛋糕的流水號(所有廚師共通)
    public MakerThread(String name, Table table, long seed) {
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }
    public void run() {
        try {
            while (true) {
                Thread.sleep(random.nextInt(1000));
                String cake = "[ Cake No." + nextId() + " by " + getName() + " ]";
                table.put(cake);
            }
        } catch (InterruptedException e) {
        }
    }
    private static synchronized int nextId() {
        return id++;
    }
}

客人(消費者)定義:

public class EaterThread extends Thread {
    private final Random random;
    private final Table table;
    public EaterThread(String name, Table table, long seed) {
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }
    public void run() {
        try {
            while (true) {
                String cake = table.take();
                Thread.sleep(random.nextInt(1000));
            }
        } catch (InterruptedException e) {
        }
    }
}

桌子(隊列)定義:

public class Table {
    private final String[] buffer;
    private int tail;
    private int head;
    private int count;
 
    public Table(int count) {
        this.buffer = new String[count];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
    }
    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " puts " + cake);
        while (count >= buffer.length) {
            wait();
        }
        buffer[tail] = cake;
        tail = (tail + 1) % buffer.length;
        count++;
        notifyAll();
    }
    public synchronized String take() throws InterruptedException {
        while (count <= 0) {
            wait();
        }
        String cake = buffer[head];
        head = (head + 1) % buffer.length;
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName() + " takes " + cake);
        return cake;
    }
}

執(zhí)行:

public class Main {
    public static void main(String[] args) {
        Table table = new Table(3);
        new MakerThread("MakerThread-1", table, 31415).start();
        new MakerThread("MakerThread-2", table, 92653).start();
        new MakerThread("MakerThread-3", table, 58979).start();
        new EaterThread("EaterThread-1", table, 32384).start();
        new EaterThread("EaterThread-2", table, 62643).start();
        new EaterThread("EaterThread-3", table, 38327).start();
    }
}

三、模式講解
Producer-Consumer模式的角色如下:

  • Data(數(shù)據(jù))參與者
    Data代表了實際生產(chǎn)或消費的數(shù)據(jù)综苔。
  • Producer(生產(chǎn)者)參與者
    Producer會創(chuàng)建Data惩系,然后傳遞給Channel參與者。
  • Consumer(消費者)參與者
    Consumer從Channel參與者獲取Data數(shù)據(jù)如筛,進(jìn)行處理堡牡。
  • Channel(通道)參與者
    Channel從Producer參與者處接受Data參與者,并保管起來杨刨,并應(yīng)Consumer參與者的要求晤柄,將Data參與者傳送出去。為確保安全性芥颈,Producer參與者與Consumer參與者要對訪問共享互斥。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末赚抡,一起剝皮案震驚了整個濱河市爬坑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌涂臣,老刑警劉巖盾计,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異赁遗,居然都是意外死亡署辉,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進(jìn)店門岩四,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哭尝,“玉大人,你說我怎么就攤上這事剖煌〔酿校” “怎么了?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵耕姊,是天一觀的道長侠姑。 經(jīng)常有香客問我,道長箩做,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任妥畏,我火速辦了婚禮邦邦,結(jié)果婚禮上安吁,老公的妹妹穿的比我還像新娘。我一直安慰自己燃辖,他們只是感情好鬼店,可當(dāng)我...
    茶點故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著黔龟,像睡著了一般妇智。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上氏身,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天巍棱,我揣著相機(jī)與錄音,去河邊找鬼蛋欣。 笑死航徙,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的陷虎。 我是一名探鬼主播到踏,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼尚猿!你這毒婦竟也來了窝稿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤凿掂,失蹤者是張志新(化名)和其女友劉穎伴榔,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缠劝,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡潮梯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了惨恭。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秉馏。...
    茶點故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖脱羡,靈堂內(nèi)的尸體忽然破棺而出萝究,到底是詐尸還是另有隱情,我是刑警寧澤锉罐,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布帆竹,位于F島的核電站,受9級特大地震影響脓规,放射性物質(zhì)發(fā)生泄漏栽连。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望秒紧。 院中可真熱鬧绢陌,春花似錦、人聲如沸熔恢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽叙淌。三九已至秤掌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鹰霍,已是汗流浹背闻鉴。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留衅谷,地道東北人椒拗。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像获黔,于是被迫代替她去往敵國和親蚀苛。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,055評論 2 355