集合-队列
队列:先进先出的集合结构。类似于List<T>,容量也是根据需要成倍的增加。
public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable
//Document文档类;DocumetManger文档控制类,用于添加文档,获取移除文档;ProcessDocuments
类用于在单独的一个线程中处理队列中的文档。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace AbstractN { public 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; } } public class DocumentManager { Queue<Document> docs = new Queue<Document>(); public void AddDocument(Document document) { lock (this) { docs.Enqueue(document); } } public Document GetDocument() { Document doc = null; lock (this) { doc = docs.Dequeue(); } return doc; } public bool isHavDoc() { return docs.Count > 0; } } public class ProcessDocument { private DocumentManager documentManager; protected ProcessDocument(DocumentManager dm) { this.documentManager = dm; } protected void Run() { while (true) { if (documentManager.isHavDoc()) { Document doc = documentManager.GetDocument(); Console.WriteLine("文档标题为:{0}", doc.Title); } Thread.Sleep(new Random().Next(20)); } } public static void Start(DocumentManager dm) { new Thread(new ProcessDocument(dm).Run).Start(); } } class Program { static void Main(string[] args) { DocumentManager dm = new DocumentManager(); ProcessDocument.Start(dm); for (int i = 0; i < 100; i++) { dm.AddDocument(new Document("Title" + i.ToString(), "Content" + i.ToString())); Console.WriteLine("增加文档:" + i.ToString()); Thread.Sleep(new Random().Next(20)); } Console.Read(); } } }
人生无处不代码,没有代码不人生。