标签:
Document类:
class Document { public string Title { get; private set; } public string Content { get; private set; } public Document(string title, string content) { this.Title = title; this.Content = content; } }
DocumentManager类:
class DocumentManager { private readonly Queue<Document> documentQueue = new Queue<Document>(); public bool IsAvailable { get { return documentQueue.Count > 0; } } public void AddDocument(Document doc) { lock (this) { documentQueue.Enqueue(doc); } } public Document GetDocument() { Document doc = null; lock (this) { doc = documentQueue.Dequeue(); } return doc; } }
ProcessDocuments类:
class ProcessDocuments { private DocumentManager dm; protected ProcessDocuments(DocumentManager dm) { this.dm = dm; } protected void Run() { while (true) { if (dm.IsAvailable) { Document doc = dm.GetDocument(); Console.WriteLine("processing document {0}", doc.Title); } Thread.Sleep(new Random().Next(20)); } } public static void Start(DocumentManager dm) { new Thread(new ProcessDocuments(dm).Run).Start(); } }
应用层:
class Program { static void Main(string[] args) { var dm = new DocumentManager(); ProcessDocuments.Start(dm); for (int i = 0; i < 100; i++) { Document doc = new Document("Doc" + i.ToString(), "content"); dm.AddDocument(doc); Console.WriteLine("Added document {0}", doc.Title); Thread.Sleep(new Random().Next(20)); } Console.ReadLine(); } }
标签:
原文地址:http://www.cnblogs.com/laixiancai/p/4388934.html