110,546
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MutiThreadSynchronizationTest2
{
class Program
{
//test2 used
static void Main(string[] args)
{
Producer producer = new Producer();
Customer customer = new Customer();
Thread produceThread = new Thread(new ThreadStart(producer.Produce));
Thread consumeThread = new Thread(new ThreadStart(customer.Consume));
Console.WriteLine("start\n");
DateTime startTime = DateTime.Now;
produceThread.Start();
Thread.Sleep(50);
consumeThread.Start();
produceThread.Join();
consumeThread.Join();
produceThread.Abort();
consumeThread.Abort();
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
Console.WriteLine("Used" + ts.TotalMilliseconds);
Console.ReadLine();
}
}
public static class ProductQueue
{
public static Queue<Product> productQueue = new Queue<Product>();
}
public class Product
{
public Product(string content)
{
Content = content;
}
private string _content;
public string Content
{
get
{
return _content;
}
set
{
_content = value;
}
}
public override string ToString()
{
return Content;
}
}
public class Producer
{
public void Produce()
{
for (int count = 0; count < 5000; count++)
{
// doing something;
Thread.Sleep(5);
Random ra = new Random();
int c = ra.Next(2, 6);
//enqueue 1-5 products
for (int i = 1; i < c; i++)
{
if (ProductQueue.productQueue.Count > 2)
{
ProductQueue.productQueue.Enqueue(new Product(i.ToString()));
}
else
{
lock (ProductQueue.productQueue)
{
ProductQueue.productQueue.Enqueue(new Product(i.ToString()));
}
}
}
}
}
}
public class Customer
{
public void Consume()
{
while (true)
{
//system is doint something else
Thread.Sleep(2);
if (ProductQueue.productQueue.Count > 0)
{
if (ProductQueue.productQueue.Count > 2)
{
ProductQueue.productQueue.Dequeue();
}
else
{
lock (ProductQueue.productQueue)
{
ProductQueue.productQueue.Dequeue();
}
}
}
else
{
break;
}
}
}
}
}
Thread.Sleep(2);
if (ProductQueue.productQueue.Count > 0)
{
if (ProductQueue.productQueue.Count > 2)
{[code=C#]
[/code]这样的程序吧!