using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DocumentManager dm = new DocumentManager();
ProcessDocument.Start(dm);
for (int i = 0; i < 1000; i++)
{
Document doc = new Document("Doc " + i, "Content");
dm.AddDocument(doc);
Console.WriteLine("Added document Doc "+ i);
Thread.Sleep(new Random().Next(20));
}
}
}
public class DocumentManager
{
private readonly Queue<Document> documentQueue = new Queue<Document>();
public void AddDocument(Document doc)
{
lock (this)
{
documentQueue.Enqueue(doc);
}
}
public Document GetDocument()
{
Document doc = null;
lock (this)
{
doc = documentQueue.Dequeue();
}
return doc;
}
public bool IsDocumentAvailable
{
get {
return documentQueue.Count > 0;
}
}
}
public class ProcessDocument
{
private DocumentManager documentManager;
protected ProcessDocument(DocumentManager dm)
{
this.documentManager = dm;
}
public static void Start(DocumentManager dm)
{
new Thread(new ProcessDocument(dm).Run).Start();
}
protected void Run()
{
while (true)
{
if (documentManager.IsDocumentAvailable)
{
Document doc = documentManager.GetDocument();
Console.WriteLine("Processing document {0}",doc.Title);
}
Thread.Sleep(new Random().Next(20));
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DocumentManager dm = new DocumentManager();
ProcessDocument.Start(dm);
for (int i = 0; i < 1000; i++)
{
Document doc = new Document("Doc " + i, "Content");
dm.AddDocument(doc);
Console.WriteLine("Added document Doc "+ i);
Thread.Sleep(new Random().Next(20));
}
}
}
public class DocumentManager
{
private readonly Queue<Document> documentQueue = new Queue<Document>();
public void AddDocument(Document doc)
{
lock (this)
{
documentQueue.Enqueue(doc);
}
}
public Document GetDocument()
{
Document doc = null;
lock (this)
{
doc = documentQueue.Dequeue();
}
return doc;
}
public bool IsDocumentAvailable
{
get {
return documentQueue.Count > 0;
}
}
}
public class ProcessDocument
{
private DocumentManager documentManager;
protected ProcessDocument(DocumentManager dm)
{
this.documentManager = dm;
}
public static void Start(DocumentManager dm)
{
new Thread(new ProcessDocument(dm).Run).Start();
}
protected void Run()
{
while (true)
{
if (documentManager.IsDocumentAvailable)
{
Document doc = documentManager.GetDocument();
Console.WriteLine("Processing document {0}",doc.Title);
}
Thread.Sleep(new Random().Next(20));
}
}
}
}
作者:黄聪
出处:http://www.cnblogs.com/huangcong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/huangcong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。