這是種模式在現實生活中的例子很多:
郵局寄信
生產者:你,消費者:投遞員,任務列表:郵筒
你寫信然後扔到郵筒中去,給任務列表中新增了乙個任務。投遞員取走有郵筒裡的信,消費掉任務列表裡的乙個任務。
郵局這樣做的好處在於:
1.解耦 你不必去認識投遞員,萬一認識的那個投遞員不幹了,你又要重新認識乙個投遞員。
2.支援併發 你不必在某個地點傻等著投遞員,同時,投遞員也不需挨家挨戶的問,哪家需要寄信。
生產者:建立任務,新增到任務列表中,例如新增一篇隨筆。
消費者:將任務列表中,某一篇隨筆新增到索引庫中,這樣在搜尋的時候,才能夠搜尋出來新發的隨筆。
建立索引庫是耗時很長的工作,所以啟動有乙個消費者執行緒一直保持對indexwriter寫的狀態,有新任務進入的時候對indexwriter寫入,寫入完成之後關閉。然後下次while迴圈掃瞄的時候判斷如果佇列彙總沒有任務,則sleep5秒鐘後再判斷,防止不斷判斷給伺服器cpu壓力。
indexmanager.cs**:
public class indexmanager乙個winform例子更佳能夠體現這個模式。private static indexmanager instance = new indexmanager();
public static indexmanager instance()
//任務列表
private listjobs = new list();
//啟動消費者執行緒
public void start()
//建立索引
private void index()
//為什麼每次迴圈都要開啟、關閉索引庫。因為關閉索引庫以後才會把寫入的資料提交到索引庫中。也可以每次操作都「提交」(參考lucene.net文件)
string indexpath = "c:/cmsindex";
fsdirectory directory = fsdirectory.open(new directoryinfo(indexpath), new nativefslockfactory());
bool isupdate = indexreader.indexexists(directory);
"索引庫存在狀態" + isupdate);
if (isupdate)
}indexwriter writer = new indexwriter(directory, new panguanalyzer(), !isupdate, lucene.net.index.indexwriter.maxfieldlength.unlimited);
//後台執行緒的實際工作
processjobs(writer);
writer.close();
directory.close();//不要忘了close,否則索引結果搜不到
"全部索引完畢");
}}
//後台執行緒工作
private void processjobs(indexwriter writer)
string title = art.title;
string body = art.content;//去掉標籤
document document = new document();
//只有對需要全文檢索的字段才analyzed
document.add(new field("number", job.id.tostring(), field.store.yes, field.index.not_analyzed));
document.add(new field("title", title, field.store.yes, field.index.not_analyzed));
document.add(new field("body", body, field.store.yes, field.index.analyzed, lucene.net.documents.field.termvector.with_positions_offsets));
writer.adddocument(document);
"索引" + job.id + "完畢");}}
}//新增任務
public void addarticle(int artid)
//刪除任務
public void removearticle(int artid)
}/// /// 索引任務
///
class indexjob
public jobtype jobtype
}enum jobtype
啟動後台執行緒,向文字框中輸入值,然後生產,listbox中經過5秒之後,才能顯示出來剛剛新增文字。
//新增任務列表
private void button1_click(object sender, eventargs e)
}private void button2_click(object sender, eventargs e)
private void start()
//工作
private void processdo()
foreach (var s in joblist.toarray())
;listbox1.invoke(d, s);
joblist.remove(s);//消費了商品就把商品從「倉庫」中移除掉}}
}}delegate void mydelegate(string s);
生產消費模式
package com.phone.week5.day3 有乙個倉庫放字元的,它有乙個生產字元的方法,也有乙個拿字元的方法 倉庫裡只能有乙個字元 有乙個生產者,可以呼叫倉庫裡生產字元的方法 有乙個消費者,可以呼叫倉庫裡拿字元的方法 兩個人不能同時生產或拿 1.建立乙個共享資源類 2.建立生產者 3....
生產消費模式
生產者producer 生產某個物件 共享資源 放在緩衝池中,然後消費者從緩衝池中取出這個物件。也就是生產者生產乙個,消費者取出乙個。這樣進行迴圈。生產者 class producer implements runnable override public void run catch interr...
java 生產消費者模式 一
需求 一瓶酒兩元,兩個瓶子換一瓶酒,四個瓶蓋換一瓶酒,那麼買100瓶酒最少需要多少錢!實現方法有很多種,這裡我採用最簡單的synchronized 同步實現 瓶子和瓶蓋換酒有四種可能 1 瓶子 2 並且 蓋子 4 可以一次換兩瓶酒,換完後,會多兩個瓶子和瓶蓋 2 瓶子 2 且 蓋子 4 可以換一瓶酒...