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/archive/2010/05/13/1734500.html,如需转载请自行联系原作者